Sign in to follow this  

[C++] Inheritance with public base methods

This topic is 2552 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi I was wondering what is the biggest different between these 2 methods

class base
{
public:
virtual void apple() = 0;
};

class derived : public base
{
private: //declare private
void apple() { std::cout << "apple\n"; }
};




and


class base
{
public:
virtual void apple() = 0;
};

class derived : public base
{
public: //declare public
void apple() { std::cout &lt;&lt; "apple\n"; }
};



wouldn't both method allow me to do something like

derived d;
base& b = d;
b->apple();




what would be the motivation behind having the derived class members as private instead of public (if any)?

regards

Share this post


Link to post
Share on other sites
Quote:
Original post by littlekid
what would be the motivation behind having the derived class members as private instead of public (if any)?
regards


Well if the function is under public, why do you really need to make it private in the first place? why not just use protected since you can override it and still keep the hiding of the function from the outside world?

Share this post


Link to post
Share on other sites
In short: In the example you provide it makes no difference!

Long version: It is an important decision whether to make virtual method public, protected or private for a plethora of reasons.

Read an extensive discussion here:
http://www.gamedev.net/community/forums/topic.asp?topic_id=270154&PageSize=25&WhichPage=1

Or just the article that spawned it (it's very good):
http://www.gotw.ca/publications/mill18.htm

HTH!

Share this post


Link to post
Share on other sites
Most likely the implementor is intending to do something like "explicit interfaces" .. where the base defines the public interface, then the derived class implement the interfaces that are only visible via the interface. A mostly silly idea in C++ and not common at all.

I can't claim this is their intention for sure.

Also, 1 other detail is they may be intending to simulate "final" where further derived classes cannot further override the method.

Once again, I cannot be sure. And would have to double check my spec to even know what that would do in practice.

Share this post


Link to post
Share on other sites

This topic is 2552 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this