override a public function to protected

G

Guest

If I have a class A that has a virtual public function DoSomething()
Class A
{
public:
virtual void DoSomething();
}

then I override this function to protected is class B
Class B: public Class A
{
protected:
void DoSomething();
}

Is this valid? Thanks!

WJ
 
P

pvdg42

WJ said:
If I have a class A that has a virtual public function DoSomething()
Class A
{
public:
virtual void DoSomething();
}

then I override this function to protected is class B
Class B: public Class A
{
protected:
void DoSomething();
}

Is this valid? Thanks!

WJ

Ignoring the syntax errors in your code, if your question is whether or not
it's syntactically legal in C++ (VC 8) to make the override protected, the
answer is yes. I'm interested to know what you want to achieve by doing
this, as if there is no class derived from B, it simply makes the override
version unusable.
 
P

pvdg42

WJ said:
If I have a class A that has a virtual public function DoSomething()
Class A
{
public:
virtual void DoSomething();
}

then I override this function to protected is class B
Class B: public Class A
{
protected:
void DoSomething();
}

Is this valid? Thanks!

WJ

Should have said "override is unusable outside B if no class is derived from
B".
 
G

Guest

OK, I'll keep on using the example.
in class A, DoSomething() is declared as public, I thought the funciton
should be protected, since it is not used outside.

Class A is in a library, which I can't change, so I wanted to change
DoSomething() to protected in class B.

Thanks for answering the question!

WJ
 
P

pvdg42

WJ said:
OK, I'll keep on using the example.
in class A, DoSomething() is declared as public, I thought the funciton
should be protected, since it is not used outside.

Class A is in a library, which I can't change, so I wanted to change
DoSomething() to protected in class B.

Thanks for answering the question!
Well, that's certainly a valid case I hadn't thought of! Thanks for telling
me!
 
B

Ben Voigt

pvdg42 said:
Should have said "override is unusable outside B if no class is derived
from B".

In any case, it's pointless to try to reduce the visibility like that...

B* someB;
static_cast<A*>(someB)->DoSomething();

is perfectly legal.

If you want to hide access to A's members from users of B, then you have to
use non-public inheritance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top