This pointer of base class will be able to temper functions and variables of its own class and can still point to derived class object. A base class pointer can point to a derived class object we can only access base class membera using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
The program demonstrates inheritance in object-oriented programming using C++. It defines a base class car with a single method start() that prints the message "Car Start". Then it defines a derived class BMW, which inherits from the car base class and adds a new method AdvanceGear() that prints the message "BMW Advance Gear".
In the main() function, an object b of class BMW is created. Then a pointer p of type car is created and assigned the address of b. Since BMW is derived from car, a pointer of type car can point to an object of type BMW.
Finally, the start() method of the car class is called using the p pointer. This demonstrates the concept of virtual functions in C++, where a function in the base class can be overridden by a function in the derived class.
Note that the commented-out lines in main() demonstrate an alternate way to call the methods directly on the object o of class BMW.
//Base Class Pointer derived Class Object #include<iostream> using namespace std; class car //Base Class { public: void start() { cout<<"Car Start"<<endl; } }; class BMW:public car //Derived Class { public: void AdvanceGear() { cout<<"BMW Advance Gear"<<endl; } }; int main() { /*BMW o; o.start(); o.AdvanceGear();*/ BMW b; car *p=NULL; p=&b; p->start(); return 0; }
Car StartTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions