Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base-derived class relationship

I have this doubt on base-derived class relationship.

i know when we derive an class from the base class, the derived class would have all the information about the base class. but the base class wouldnt know anything about the derived class.

so, why is this acceptable?

Base *b=new Derived();

and not

Derived *d=new Base();.

and basically i need to understand the need of the first statement? i mean, what is the use of assigning the derived class object to the base class pointer?

Note : This is not an assignment. im in the early stage of learning programming. so basically need to understands the bits and pieces. Please ignore if this is very basic and already asked question.

like image 476
Umal Stack Avatar asked Dec 21 '22 07:12

Umal Stack


1 Answers

When the Derived class object is made the Base class constructor is called first. The Derived class object contains the Base class object. This allows it to call its Base functions. Whereas a Base class object does not contain a Derived class object

enter image description here

Base *b=new Derived(); 

is useful in situations where you can use a single function to handle all derived class objects.

Consider,

Parent class : Animal Derived classes: Dog, Cat etc

Now, you have a function

void doSomethingtoTheAnimal(//take Animal here);

If you were not allowed to assign a base class object to parent reference variable. You will have to create a separate function for Dog, Cat and so on.

void doSomethingtoTheAnimal(Cat *b) or void doSomethingtoTheAnimal(Dog *b)

However, with polymorphism you can use void doSomethingtoTheAnimal(Base *b); Then you can do

Base *b1 = new Dog() or Base *b2 = new Cat();

and use the same function doSomethingtoTheAnimal(b1) or doSomethingtoTheAnimal(b2)

Also, the base class pointer when pointing to a derived class object can only call either the functions in parent class or overriden ones in child class. It is not aware of functions defined exclusively in the child class

like image 198
Suvarna Pattayil Avatar answered Dec 24 '22 00:12

Suvarna Pattayil