I'm trying to put new values when I intialise the object from the derived class, but I just can't figure out why it's not working. Can someone please tell me why this doesn't work?
It says "name" and "age" on line 34 are undefined. Also, if I leave the parentheses on line 42 empty then all the foo's from line 44-47 throw an "expression must have a class type" error.
DerivedClass::DerivedClass(int num2, int num3) :
BaseClass(name, age), //Thought something like this was possible
On that second line, you're trying to call the BaseClass constructor, and you're passing it two parameters. Parameters called "name" and "age".
At this point, the only values you have to work with are the parameters you passed in to the DerivedClass constructor on the first line. What are they called? "num2" and "num3".
So where exactly are "name" and "age" coming from?
DerivedClass foo("Mr Tickle",0,0,0);
Here's an attempt to call a DerivedClass constructor with four parameters. There is no such constructor. There is no DerivedClass constructor that takes four parameters.
Hmmm. I think I'm missing some understanding of how inheritance and constructors work.
Name and age are in the BaseClass constructor. it was my understanding that DerivedClass would inherit these so that "foo" would have 4 data members in total. How do I initialise an object of DerivedClass like I'm attempting here? Does it not have 4 data members?
Yes, DerivedClass does inherit the base class variables. (sizeof(Derived) >= sizeof(Base))
But what you wrote doesn't make sense semantically. Think of the constructor for DerivedClass as just being another function (albeit special because it doesn't have a return type). You're passing name and age into the construction of BaseClass, but you never gave values to name and age.
Question: What do you think the values of name and age are on line 34?
As Repeater said, you don't have a 4x-arg constructor for your derived class, so line 42 doesn't make sense.
A 4x-arg constructor is not automatically created, you must make it.
You need to do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class DerivedClass : public BaseClass
{
public:
int m_num2;
int m_num3;
DerivedClass(string, int, int, int);
};
DerivedClass::DerivedClass(string name, int age, int num2, int num3) :
BaseClass(name, age),
m_num2(num2),
m_num3(num3)
{}
int main()
{
DerivedClass foo("Mr Tickle", 2, 3, 4);
}