Inheritance in C++

I was casually looking at some material on C++ on the web today when I came across this. The first read messed up with my head.

After a while I thought of doing some experiments with g++, because for some strange reason the phrase “private virtual functions” popped up in my head. And I thought that was weired. My formal education in Computer Science told me that there was no way we could have private virtual functions. So I decided to write a simple test and check with g++. The test program goes something like this.

class AbstractBaseClass
{
public:
virtual void PublicFunction() = 0;

protected:
virtual void ProtectedFunction() = 0;

private:
virtual void PrivateFunction() = 0;

// Declare Friends
friend void ProbeClass(AbstractBaseClass* ptr);
};

class DerivedClass1 : public AbstractBaseClass
{
public:
void PublicFunction() { cout << "DerivedClass1::PublicFunction()" << endl; }
void ProtectedFunction() { cout << "DerivedClass1::ProtectedFunction()" << endl; }
void PrivateFunction() { cout << "DerivedClass1::PrivateFunction()" << endl; }
};

class DerivedClass2 : public AbstractBaseClass
{
public:
void PublicFunction() { cout << "DerivedClass2::PublicFunction()" << endl; }
protected:
void ProtectedFunction() { cout << "DerivedClass2::ProtectedFunction()" << endl; }
private:
void PrivateFunction() { cout << "DerivedClass2::PrivateFunction()" << endl; }
};

void ProbeClass(AbstractBaseClass* ptr)
{
ptr->PublicFunction();
ptr->ProtectedFunction();
ptr->PrivateFunction();
}

int main()
{
DerivedClass1 object1;
DerivedClass2 object2;

ProbeClass(&object1);
ProbeClass(&object2);

return 0;
}

To my surprise the above program compiled well on g++. And whats more, I did get the output as expected.

prashanth@vcl1:~/temp$ ./a.out
DerivedClass1::PublicFunction()
DerivedClass1::ProtectedFunction()
DerivedClass1::PrivateFunction()
DerivedClass2::PublicFunction()
DerivedClass2::ProtectedFunction()
DerivedClass2::PrivateFunction()

Private virtual functions do exist !!!. This is my first time with a “private” virtual function. I hope the concept wont appear weired to me anymore.


Posted

in

by