Explain the Golden Rule of Inheritance with example in C++?
Golden rule of Inheritance states that
"A parent can hold reference to its childs but allows to access only those methods of child whose signature is provided from the child".
Example 1
WAP having a class A with a method aboutme() to show a message "This is A".
Create the child class of A as B and create the same function aboutme() in it to show a message "This is B" along with one additional function welcome() to show a message "Welcome to B".
Create another child class of B as C and create the same function aboutme() to show a mesasge "This is C".
Create an entry point with reference of parent class A and three instance of classes A, B and C then try to compile the code and run the code.
See what happens
#include<iostream>
using namespace std;
class A
{
public:
void aboutme()
{
cout <<"This is A" << endl;
}
};
class B: public A
{
public:
void aboutme()
{
cout <<"This is B" << endl;
}
void welcome()
{
cout <<"Welcome to B" << endl;
}
};
class C: public B
{
public:
void aboutme()
{
cout <<"This is C" << endl;
}
};
main()
{
A *p;
p=new A();
p->aboutme();
p=new B();
p->aboutme();
p=new C();
p->aboutme();
}
"A parent can hold reference to its childs but allows to access only those methods of child whose signature is provided from the child".
Example 1
WAP having a class A with a method aboutme() to show a message "This is A".
Create the child class of A as B and create the same function aboutme() in it to show a message "This is B" along with one additional function welcome() to show a message "Welcome to B".
Create another child class of B as C and create the same function aboutme() to show a mesasge "This is C".
Create an entry point with reference of parent class A and three instance of classes A, B and C then try to compile the code and run the code.
See what happens
#include<iostream>
using namespace std;
class A
{
public:
void aboutme()
{
cout <<"This is A" << endl;
}
};
class B: public A
{
public:
void aboutme()
{
cout <<"This is B" << endl;
}
void welcome()
{
cout <<"Welcome to B" << endl;
}
};
class C: public B
{
public:
void aboutme()
{
cout <<"This is C" << endl;
}
};
main()
{
A *p;
p=new A();
p->aboutme();
p=new B();
p->aboutme();
p=new C();
p->aboutme();
}
Note: Code get compiled normall and executes it
Now try to call the function welcome() of class B, it will generate an error since A class do not have welcome() function because of Golden Rule of Inheritance.
#include<iostream>
using namespace std;
class A
{
public:
void aboutme()
{
cout <<"This is A" << endl;
}
};
class B: public A
{
public:
void aboutme()
{
cout <<"This is B" << endl;
}
void welcome()
{
cout <<"Welcome to B" << endl;
}
};
class C: public B
{
public:
void aboutme()
{
cout <<"This is C" << endl;
}
};
main()
{
A *p;
p=new A();
p->aboutme();
p=new B();
p->aboutme();
p->welcome(); //error
p=new C();
p->aboutme();
}
Comments
Post a Comment