Can someone explain to me why a parent class object would be
Can someone explain to me why a parent class object would be assigned to a child class object? What purpose does it serve?
#include
#include
using namespace std;
class Pet
{
public:
string name;
virtual void print() const{};
};
class Dog : public Pet
{
public:
string breed;
virtual void print()const{} ;
};
int main()
{
Dog d;
Pet p;
d.name = \"big\";
d.breed = \"German Shepard\";
p = d;
}
Solution
parent class object reference is assigned child object so as to generalize the child object and use it for operations with other child objects that belong to same parent class.
Example : if we have another class called Cat that extends parent Pet ,when we need to compare cat and dog objects we need to convert both objects to its parent type .instead of that we can assign each to different parent class references.
Like Dog d=new Dog(); Pet p1=d;
Cat c=new Cat();Pet p2=c;
