C Programming 1 If a data member is declared as private prot

C++ Programming

1) If a data member is declared as private, protected or public in a base class, discuss how it can or cannot be accessed in a public member function of a derived class.

2) Discuss the difference between overloading and overriding a member function in a derived class.

3) Give an example of a situation where it is necessary to define a virtual destructor.

Solution

Q1. If a data member is declared as private, protected or public in a base class, discuss how it can or cannot be accessed in a public member function of a derived class.

ANS.

Let us consider two classes:

class base{

private: int a;

protected: int b;

public: int c;

}

class derived: public base{

// a is not accessible

// b is protected and accessible

// c is directly accessible

}

Here, we are inheriting the base class to the derived class as public. So in this case,

>> private members from base class are not accessible in the derived class.

>> protected members are accessible in the derived class in protected mode (protected and private can be distinguished on the only fact that private members are completely private members of the base class and cannot be inherited whereas protected members can be inherited and are accessible by derived classes, but not by any other classes).

>> public members are accessible directly to the derived classes as well as any other classes.

Q2. Discuss the difference between overloading and overriding a member function in a derived class.

ANS.

OVERLOADING:

Overloading means that we are defining two different methods with the same name, which differ only on the basis of number of parameters. Overloading cannot be done from base class to derived class in C++. The compiler only looks for an overloaded method in the scope of the single class. If it does not find the overloaded method in the derived class itself, it won\'t move to the base class to search for it and will throw an error.

OVERRIDING:

Overriding is when we declare 2 different methods with same name and same number of arguments but in 2 different scopes i.e. base class and derived class. In such a case, if an object of base class is made to call that method, it will automatically call the method from the base class whereas an object of derived class will automatically call the overridden method from derived class. In order to call the base class method from derived class, we need to use scope resolution methodolgy like this:

class derived : public base{

base::OverriddenMethodName();

}

C++ Programming 1) If a data member is declared as private, protected or public in a base class, discuss how it can or cannot be accessed in a public member fun
C++ Programming 1) If a data member is declared as private, protected or public in a base class, discuss how it can or cannot be accessed in a public member fun

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site