Mr. Bala
Mr. Bala

Reputation: 31

C++ - inheritance

I was expecting the following code snippet to give compile error since derived class will not have priv_var which I am trying to access in pub_fun(). But it compiled and I got below mentioned output. Can someone explain the theory behind this?

class base {

private:
  int priv_var = 90;

public:
  int pub_fun();

} b;

class derived : public base {
} d;

int base::pub_fun() { cout << priv_var << "\n"; }

int main() {
  d.pub_fun();
  return 0;
}

output:

90

Upvotes: 3

Views: 175

Answers (2)

dxiv
dxiv

Reputation: 17628

1. Class derived has access to public (and protected) members of class base, by the rules of public inheritance.

2. Members of class base have access to all other base members, because they belong to the same class.

d.pub_fun(); is valid because of 1. and int base::pub_fun() { cout << priv_var << "\n"; } is valid because of 2. so everything compiles and works without a problem.

I was expecting the following code snippet to give compile error since derived class will not have priv_var which I am trying to access in pub_fun().

You are conflating two separate steps into one here. The derived class does indeed not have access to base::priv_var, but derived never attempts to use base::priv_var. All that derived d; does is call the public member function pub_fun(). From there on it is a matter of pub_fun implementation, which derived needs not know or care about. In your example, the implementation of pub_fun happens to use a private base variable, which it is perfectly fine to do since it is a member function of the same base class.

In other cases, class derived could be your code, and base could be a library class to which you don't even have the source code. You could always call public member functions from base even though you would have no idea what their implementation uses internally.

Upvotes: 1

Tommy Andersen
Tommy Andersen

Reputation: 7220

It compiles since the method pub_fun is declared in the base class. That is the reason it has access to the private member priv_var. If you had created a method in derived and attempted to access priv_var you would have seen a compile time error.

Upvotes: 3

Related Questions