1

I have a class Airplane:

class Airplane {
    private:
        int value;
   public:
        // some public functions that arent relevant
};

and then another class that derives from Airplane

class Model : public Airplane {
    private:
        bool flag;
    public:
       // some functions
};

What I need to do is create a pointer of type airplane that points to the child class, aka model.

Like so: Airplane* A = new Model(); Then I can use A->functions to access the public functions of airplane to modify airplanes private data members.

My problem is I need to modify the private data members of Model. I created public member functions in model to change models private members, but it doesnt let me do A->modelfunctions. Is there a way to modify the Model private members with my system above?

My instructions were to create a dynamic instance of a Model and hold the address in an Airplane pointer. I want to do this while being able to modify private variables from both classes, either directly or through public functions. Right now I can modify "value" from airplane, but not "flag" from model using the Airplane* A = new Model(); system.

Thank you.

Max
  • 15
  • 3
  • You need to make `Airplane` polymorphic by defining [virtual member functions](https://en.cppreference.com/w/cpp/language/virtual) then [override them](https://en.cppreference.com/w/cpp/language/override) in the `Model` class. – Patrick Roberts Aug 09 '20 at 00:05
  • Can’t you make the variables protected rather than private? Won’t they still be accessed by the derived class? – Andrew Truckle Aug 09 '20 at 00:05
  • Not sure polymorphism helps. He wants to access the variables from both model and airplane. – Andrew Truckle Aug 09 '20 at 00:06
  • 1
    @AndrewTruckle the override can access variables in `Model`, and delegate access to the variables in the `Airplane` by calling the base function. – Patrick Roberts Aug 09 '20 at 00:07
  • @PatrickRoberts would you be able to provide an example of how I make them virtual? Im still new to c++ so not sure how to do that. Thank you. – Max Aug 09 '20 at 00:28
  • If all you are trying to do is set the value of `flag`, without any side effects, then you shouldn't use a pointer to an `Airplane` but rather to a `Model`. Polymorphism doesn't make sense in that case. – Andreas T Aug 09 '20 at 00:31

0 Answers0