Advertisement
class derived-class-name : visibility-mode base-class-name
{
//members of derived class
}
#include<iostream>
using namespace std;
//Base class
class Y
{
public:
int a;
int get_a();
private:
int b;
int get_b();
};
//Definition of get_a() function of Y class
int Y :: get_a()
{
return a;
}
//Definition of get_b() function of Y class
int Y :: get_b()
{
return b;
}
//Derived class
class X : public Y
{
};
int main()
{
X ob; //Making an object of derived class
ob.a = 10; //Accessing an inherited property 'a'
cout<<" The value in a is : " << ob.get_a(); //Accessing an inherited method
return 0;
}
The value in a is : 10
#include<iostream>
using namespace std;
class Y
{
public:
int a;
void get_a();
private:
int b;
void get_b();
};
//Definition of get_a() function of Y class
void Y :: get_a()
{
cout<<a;
}
//Definition of get_b() function of Y class
void Y :: get_b()
{
cout<<b;
}
class X : private Y
{
public:
void access_a();
};
void X :: access_a()
{
a = 10;
get_a();
}
int main()
{
X ob;
//ob.a = 10; will not work because a is private in derived class, X
//ob.get_a(); will not work because get_a() function is private in derived class, X
ob.access_a(); //works, because access_a() is declared public in derived class, X
return 0;
}
The value in a is : 10
Advertisement
#include<iostream>
using namespace std;
class Y
{
public:
int a;
void get_a();
protected:
int b;
void get_b();
private:
int c;
void get_c();
};
//Definition of get_a() function of Y class
void Y :: get_a()
{
cout<<"The value of a is : " << a << "\n";
}
//Definition of get_b() function of Y class
void Y :: get_b()
{
cout<<"The value of b is : " << b << "\n";
}
//Definition of get_c() function of Y class
void Y :: get_c()
{
cout<<c;
}
class X : protected Y
{
public:
void access_ab();
};
void X :: access_ab()
{
a = 10;
b = 10;
get_a();
get_b();
}
int main()
{
X ob;
//ob.a = 10; will not work because a is private in derived class, X
//ob.b = 10; will not work because b is protected in derived class, X
ob.access_ab(); //works, because access_a() is declared public in derived class, X
return 0;
}
The value in a is : 10
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement