using the return type as pointer to derived class

2019-08-28 03:01发布

问题:

Is it possible to have a function in base class which will have return type as pointer to derived class? the main objective is for later use where you use Base and Derived Class to set values.

Base B1;
B1.SetName("nameOfBase");
Derived* D1 = B1.CreateDerived("DerivedFromBase");//CreateDerived method will be in class Base
D1->SetMinPoint(0,1);//this method will be implemented in derived class
D1->SetMaxPoint(4,4);//this method will be implemented in derived class

I am having problem in implementation, i did something like

class Base
{
public:
  Base();
  bool SetName(char*);//or SetName(string)
  Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
  ~Base();
protected:
  char baseName[20];// or string baseName
  Derived* derivedPtr[5];
};

class Derived: public Base
{
public:
  Derived();
  bool SetName(char*);//the name given in Derived* CreateDerived(char*) will be set here
  ~Derived(); 
};

when i try to do this and run the program i get errors like

// Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
error C2143: syntax error: missing ';' before '*'
error C4430: missing type identifier: int assumed.

回答1:

Yes, it's possible. It seems to be a somewhat questionable design, but there's nothing preventing you from doing it. You just need to declare class Derived before you refer to it:

class Derived;  //forward declaration here

class Base
{
public:
  Base();
  bool SetName(char*);//or SetName(string)
  Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
  ~Base();
protected:
  char baseName[20];// or string baseName
  Derived* derivedPtr[5];
};

class Derived: public Base
{
public:
  Derived();
  bool SetName(char*); //don't forget semi-colon
  ~Derived(); 
};

And as @psur mentioned, you were also missing a semi-colon after SetName.

And I do strongly suggest using std::string instead of char* for strings in C++.



回答2:

Can't you make your CreateDerived method pure virtual and override it in the derived classes? The return type of the method in the Base class would be Base, but the overridden method in the derived class could return the Derived instance you need. I think that is the Template Method-Pattern.

Your class inheritance should always behave like an is-a relation (Derived-Class is-a Base-Class). I think your design suggestion sort of undermines this rule.