Thursday, June 29, 2023

C++ : Constructors And Destructors

Constructors are used to construct an instance of a class and initiallize the data members of a class.

In C++ initiallization of data members are mandatory.

Destructors are used to deallocate the memory occupied by the instance of a Class.

Please check the example below :

https://github.com/puthukkudi/ConstructorsAndDestructors.git

C++ : Virtual Functions

Virtual functions helps to override methods from base class.
If the Base class and the Child class  both defines the function method() then the pointer reference of Base class pointing to the object of Child class when used to call function method(); it will call the Base class function method()

i.e;

Base * base = new Child();
base->method(); // this will call the Base class method() ; unless untill you declare method() as virtual in base class.



Internal Working :

If compiler finds any virtual function it creates a static array for each class called VTable or Virtual Table. Elements of this VTable are the function pointer to each member function.Since Vtable is a static array it means its object independent.

During object creation compiler creates a secrete data member for the base class. This data memeber is called Virtual Pointer. This Virtual Pointer is inherited by the child class. Respective class instances's virtual pointer points to respective class's VTable. Hence provisioning for overriding. 

Virtual Functions can't be static as static functions are tied to a class and not to instance of a class.






Please check the example below : 

https://github.com/puthukkudi/VirtualFunction.git