0% found this document useful (0 votes)
14 views3 pages

C++ Inheritance and Polymorphism Example

The document contains two C++ programs demonstrating key concepts of object-oriented programming. The first program illustrates the use of protected data members in inheritance, showcasing how derived classes can access these members. The second program implements polymorphism using virtual functions, allowing base class pointers to invoke derived class functions dynamically.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

C++ Inheritance and Polymorphism Example

The document contains two C++ programs demonstrating key concepts of object-oriented programming. The first program illustrates the use of protected data members in inheritance, showcasing how derived classes can access these members. The second program implements polymorphism using virtual functions, allowing base class pointers to invoke derived class functions dynamically.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

/*C++ program to demonstrate use of

protected data members in inheritance*/

#include <iostream>

//class definition
class A{
private:
int a;
protected:
int p;
public:
void get_a(int a){
this->a=a;
}
void put_a(){
cout<<"a="<<a<<endl;
}
};
class B: public A{
private:
int b;
public:
void get_b(int b){
this->b=b;
}

void put_b(){
cout<<"b="<<b<<endl;
}
void get_p(int p){
this->p=p;
}

void put_p(){
cout<<"p="<<p<<endl;
}
};
int main(){
//creating object of B (derieved class)
B objB;
//get values of a,b and p
objB.get_a(10);
objB.get_b(20);
objB.get_p(30);
//print values of a,b and p
objB.put_a();
objB.put_b();
objB.put_p();

return 0;
}

how to implement polymorphism with inheritance using virtual


functions in c++ programming language?
#include <iostream>

class Base{
public:
virtual void disp(){
cout<<"disp function of Base class"<<endl;
}
};
class Derived1: public Base{
public:
void disp(){
cout<<"disp function of Derived1
class"<<endl;
}
};
class Derived2: public Base{
public:
void disp(){
cout<<"disp function of Derived2
class"<<endl;
}
};
int main(){

Base *b;
Derived1 D1;
Derived2 D2;

b= &D1;
b->disp();
b= &D2;
b->disp();

return 0;
}

You might also like