LOLtricker LOLtricker - 1 year ago 79
C++ Question

How to create an object of a derived class in a base class in c++

Hello I am trying to create a program but am having some trouble I have 3 classes called Goku vegeta Beerus with Goku being the base class and vegeta and Beerus inherting from Goku I want to create an object of vegeta called rose and an object of Beerus called god inside Goku but am getting error can anyone point out how i would do this any and all help is appreciated the program is below:

class Goku
{ public:
Goku();
˜ Goku();
string get_Name(void);
int get_power(void)
// This is what i want to do but keep getting errors
vegeta* rose;
Beerus* god;


};
class vegeta: public Goku
{
public:
vegeta(); //an intitializtion constructor
˜ vegeta();//destructor
string get_Name(void);
int get_power(void)

};
class Beerus: public Goku
{ public:
Beerus(); //an intitializtion constructor
˜ Beerus();//destructor
string get_Name(void);
int get_power(void)

};


Note the error i get are: vegeta cannot name a type
Beerus cannot name a type

Answer Source

You have an error in your class. Currently, when you do this:

vegeta* rose;
Beerus* god;

At that point, the compiler doesn't know what vegeta and Beerus are. To solve this, add the following 2 lines all the way at the beginning of your code:

class Beerus;    
class vegeta;

This tells the compiler, that if one of the above 2 classes is referenced, before being completely defined, as in instantiated, then the compiler can look ahead for the name in the rest of the file.


Live Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download