top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Private virtual function overridden as public compiles and runs?

+1 vote
172 views

The following program compiles and runs - is it correct behavior? I read §11.5 in the January 2012 working draft but couldn't reach a conclusion.

class B
{
 virtual int f() { return 42; };
};

class D : public B
{
public:
 int f() { return 43; };
};

int main()
{
 D d;
 B * pb = 
 D * pd = 
 //pb->f(); // error: B::f() is private
 pd->f(); // OK: D::f() is public
}
posted Oct 14, 2013 by Anderson

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Yes, it is the correct behavior according to the C++ standard. I think it's broken, but as it's in the standard, there's little can be done about it.

Do there a warning? there should be....

answer Oct 14, 2013 by Garima Jain
I agree. Despite being correct behavior, it allows for a weird (risky?) change to an interface and probably indicates a mistake.
Similar Questions
+2 votes

When a function is declared as virtual and when a class ? Please explain with examples.

0 votes

This code compiles on MSVC but not on G++ :

template
class B
{
public:
 static void SomeMethod()
 {
 A::SomeMethod();
 }
};

class A
{
public:
 static void SomeMethod();
};

void test()
{
 B::SomeMethod();
}

The error with g++ is :

test.cpp: In static member function "static void B::SomeMethod()":
test.cpp:7:3: error: "A" has not been declared

Is there is a option to indicate to g++ to evaluate the template functions only when a specialization is called, and not before ?

0 votes

Explain about pure virtual function

...