You are on page 1of 4

1. Private members of base class are not inherited.

#include<iostream>
using namespace std;
class Base {
private:
int i, j;
public:
Base(int _i = 0, int _j = 0): i(_i), j(_j) { }
};
class Derived: public Base {
public:
void show(){
cout<<" i = "<<i<<" j = "<<j;
}
};
int main(void) {
Derived d;
d.show();
return 0;
}
Run on IDE

i=0j=0
Compiler Error: i and j are private in Base

C Compiler Error: Could not call constructor of Base

2.If a derived class writes its own method, then all functions of
base class with same name become hidden, even if signaures of
base class functions are different. In the above question, when
fun() is rewritten in Derived, it hides both fun() and fun(int) of base
class

#include<iostream>
using namespace std;
class Base
{

public:
int fun() { cout << "Base::fun() called"; }
int fun(int i) { cout << "Base::fun(int i) called"; }
};
class Derived: public Base
{
public:
int fun() { cout << "Derived::fun() called"; }
};
int main()
{
Derived d;
d.fun(5);
return 0;
}
Run on IDE
Base::fun(int i) called

B Derived::fun() called
C Base::fun() called
Compiler Error

3.We can access base class functions using scope resolution


operator even if they are made hidden by a derived class function.
#include<iostream>
using namespace std;
class Base {
public:
int fun()
int fun(int i)
};

{
{

cout << "Base::fun() called";


}
cout << "Base::fun(int i) called"; }

class Derived: public Base {


public:
int fun()
{
cout << "Derived::fun() called";
};
int main() {
Derived d;
d.Base::fun(5);
return 0;
}
Run on IDE

Compiler Error

Base::fun(int i) called

4.Object slicing
Here when derived class object when given base
class type will be changed to a base class object
Output of following program?

#include <iostream>
#include<string>
using namespace std;
class Base
{
public:
virtual string print() const
{
return "This is Base class";
}
};
class Derived : public Base
{
public:
virtual string print() const
{
return "This is Derived class";
}
};
void describe(Base p)
{
cout << p.print() << endl;
}
int main()
{
Base b;
Derived d;
describe(b);
describe(d);
return 0;
}
Run on IDE

This is Derived class


This is Base class

This is Base class


This is Derived class
This is Base class
This is Base class

D Compiler Error

5.Diamond problem.multiple copies of same variable from


diff.parent classes the derived class cant differenciate
since the name is same (its taken from original parent
base class).
6.when ever a derived class object is created all the base
classes unparametrised constructors are called.

You might also like