C++ Virtual function implementation?
Solution 1
once a function is made virtual in a base class, it will be virtual for every other subclass.
public, protected and private do not affect the virtual nature of functions.
Solution 2
If You remove virtual
from the myfunction
definition in class B,
compiler will add this for You. To fill out V-Table for polymorphic types.
!!BUT!!
You will only have access to public members of class A (class B: public A)
the definition :
class B: private A
{
}
Will cause that all (even public) members of class A, will become private for class B. Simplifies You will not have an access to A public members.
To workaround You can declare some friend:
class A
{
private:
friend class B;
}
More great info HERE.
atp
Updated on November 06, 2020Comments
-
atp over 3 years
If I have in C++:
class A { private: virtual int myfunction(void) {return 1;} } class B: public A { private: virtual int myfunction(void) {return 2;} }
Then if I remove
virtual
from themyfunction
definition inclass B
, does that mean that if I had aclass C
based onclass B
, that I couldn't override themyfunction
since it would be statically compiled?Also, I'm confused as to what happens when you switch around public, and private here. If I change the definition of
myfunction
inclass B
to be public (and the one inclass A
remains private), is this some sort of grave error that I shouldn't do? I think that virtual functions need to keep the same type so that's illegal, but please let know if that's wrong.Thanks!
-
atp over 14 yearsThank you! Thanks for the visibility info.
-
stefaanv over 14 yearsThe answer is a bit confusing for me. From the answer I read that class B can not access public members he inherits from class A, which is then solved by declaring B friend of A. I don't think that would be right. B can access public and protected members from A but users of B can not access public members of A and this will not be solved by the friend declaration. Am I missinterpreting something?
-
bua over 14 yearsYes, You've missed the private inheritance from my example.
-
stefaanv over 14 yearsOkay, then I suggest you reread the info on your link: class B can access all public and protected members from his privately inherited class A, friend or not friend.
-
Freshzak187 about 14 yearsBy making your virtual functions protected or private you can hint to the users of your class if they're required to call them in the subclass or not. gotw.ca/publications/mill18.htm
-
underscore_d over 8 yearsBeing optimistic, perhaps they meant not that B can't access the members inherited from A, but rather that an outside user of B cannot access A's (previously public) members via B's interface. Either way, this answer is poorly worded and of dubious relevance to the question.