public in parent but private in child

Take a look at following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

class Parent
{
public:
  virtual void call()
  {
    std::cout << "Parent call\n";
  }
};

class Child : public Parent
{
private:
  void call()
  {
    std::cout << "Child Call\n";
  }
};

int main()
{
  Parent *p1;
  p1 = new Child;
  p1->call();
  return 0;
}


This actually worked in linux (g++ compiler). The call p1->call() print "Child call". What does this mean? Can we say that Child::Call() is really private? Why this is even supported? What is the use?
"public" and "private" is only used within the compiler when it does static linking. Once the code is compiled, there is no such thing as "private" (for example, its not possible to overload a function that only differs on public/private).

So no, Child::Call is "not really private" and yes, this is "supported" and will work on all compilers. And no: there is not really a use for this ;-). If you want to read more about this, I recommend Scott Meyer, "Effective C++" (a bit outdated, but still a very good book about some C++ cave-eats)


Oh, and you should make the destructor of Parent virtual or your program may behave unexpected once you delete p1.

Ciao, Imi.

This is the way it works.
The call() function at first declaration is public in Parent class - it will will stay public in Child class in spite of the fact that you tried to make it private in Child class.
Some more explanation: Most C++ newcommers I encounter which wonder about your described behaviour have a problem applying the so called "Liskov's Substitution Principle" (http://en.wikipedia.org/wiki/Liskov_substitution_principle).

The part of this principle that is interesting here is:, roughly said: "Everything you can do with a base class you can do with a derrived class as well."

If you try to make a function disappear by subclassing a class, then you are trying to violate this principle in your mind. Since you now could do something with the base class (calling "call()") which you can not do with the child class.

There are places where violating LSP is a solution, but in general it is much more fatal in the long run and a clear hint of bad software design. And that may also be the reason why the guys behind C++ didn't felt bothered about providing any support to make your call illegal.
Topic archived. No new replies allowed.