In my example, I have two classes: Parent
and Child
. I'm using a vector of pointers to Parent
(vector<Parent*> v;
) and I'm inserting objects of both classes into v
. I'm trying to print the classes attributes overloading the operator <<
. My code prints the Parents attributes (name and age) and I would like to know how to print the derived attributes from Parent
and the Child
's own attribute.
class Parent{
friend ostream &operator<<(ostream &saida, Parent &parent){
out << "Name: " << parent.name << ", Age: " << parent.age << "." << endl;
return out;
}
public:
Parent(string name, int age){
this->name = name;
this->age = age;
}
string& getName(){
return name;
}
int& getAge(){
return age;
}
private:
string name;
int age;
};
class Child: public Parent{
friend ostream &operator<<(ostream &out, Child &child){
out << "Name: " << child.name << ", Age: " << child.age << ", School: " << child.school << "." << endl;
return out;
} // <- Don´t know what to do here
public:
Child(string name, int age, string school): Parent(name, age){
this->school = school;
}
string& getType(){
return type;
}
private:
string school;
};
int main(){
vector<Father*> v;
v.push_back(new Parent("Father", 30));
v.push_back(new Child("Child", 10, "School"));
for(int i = 0; i < v.size(); i++){
cout << *v[i];
}
return 0;
}
It prints:
Name: Father, Age: 30 Name: Child, Age: 10