I have written the following code:
// constructors and derived classes
#include <iostream>
using namespace std;
class Mother
{
public:
int age;
Mother()
{
cout << "Mother: no parameters: \n"
<< this->age << endl;
}
Mother(int a)
{
this->age = a;
}
void sayhello()
{
cout << "hello my name is clair";
}
};
class Daughter : public Mother
{
public:
int age;
Daughter(int a)
{
this->age = a * 2;
};
void sayhello()
{
cout << "hello my name is terry";
}
};
int greet(Mother m)
{
m.sayhello();
}
int main()
{
Daughter kelly(1);
Son bud(2);
greet(kelly);
}
and my question is this: Since kelly is an instances of a class derived from Mother it makes sense to me that I can pass it into a function that requires an object of type mother ie. greet. My question is this, is it possible to call the sayhello function from within greet such that it will say it will say "hello my name is terry" instead of "hello my name is clair".
int age;in yourDaughterclass, since that variable already exists in theMotherclass. If you declare it in theDaughterclass as well, then everyDaughterwill have two ages, which is probably not what you intended. A better approach would be to write yourDaughterconstructor like this, so that theaargument gets passed up toMother's constructor:Daughter(int a) : Mother(a*2) {}Daughteris also aMother. That doesn't make sense, but presumably because it's just an example.