nasw_264
nasw_264

Reputation: 107

Base class data member type depends on derived class

I have a question regarding polymorphism in c++:

header file

class Base {
public:
  type1 data;
};

class Derived1 : public Base {
public:
  type2 data;
};

class Derived2 : public Base {
public:
  type3 data;
};

code:

Base * obj;

if (...)
  obj = new Derived1();
else
  obj = new Dervied2();

// Do something on declared object
DoSomething( obj->data );

What should I put as type1 in base class if the type depends on the derived class being defined? The function DoSomething() will be overloaded to take in either type2 or type3.

Upvotes: 1

Views: 822

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

Here is the only (*) right incantation.

class Base {
  public:
     virtual void DoSomething() = 0;
     // no data
};

class Derived1 : public Base {
  public:
     void DoSomething() override;
  private:
      type2 data;
};

class Derived2 : public Base {
  public:
     void DoSomething() override;
  private:
      type3 data;
};

Base * obj;

if (...)
  obj = new Derived1();
else
  obj = new Derived2();

obj->DoSomething();

(*) There are other valid (as in "it compiles at runs") ways but they are not right.

Upvotes: 1

Related Questions