top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Private virtual function overridden as public compiles and runs?

+1 vote
33 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 Google+ Share Button LinkedIn Share Button Multiple Social 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
0 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

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...