Archived

This topic is now archived and is closed to further replies.

C++ classes question

This topic is 5017 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

Watch the following code:
class derivada : public base
{
public:
    derivada()
    {
        a = b = c = d = e = f = 0;
    }
    void Print(); 
};
 
Why does I have to write "public" on base class declaration for "derivada"? I tried to remove the "public" word between : and ''base'' and it works fine. I also tried to put the ''private'' and ''protected'' words there and I don''t saw any change. Does these changes make difference?

Share this post


Link to post
Share on other sites
You shouldn''t be able to access base''s methods from outside derivada''s class if base isn''t publicly derived.

Public derivation denotes an "is-a" relationship, whereas private/protected denotes "is-implemented-in-terms-of". Google for these terms.

Cédric

Share this post


Link to post
Share on other sites
Private (and protected) inheritance is the same as declaring the base as a private (data-)member except that virtual methods in the base can be overloaded by the derived class.

Share this post


Link to post
Share on other sites
you will ONLY see the difference in 2 places:

IF you try to derive a class "grandchild" from "derivada" ... then "grandchild" will not be able to use any members of "base" if "derivada" had used "private" inheritance.

A client program (non-derived object) tries to use an object of type "derivada", then they cannot access the members of "base" if "derivada" used private or protected inheiritance.

Basically, "private" and "protected" inheiritance break the "is-a" relationship one usually assumes (sometimes incorrectly) with "public" inheiritance ... the derived class in these cases is NOT substitutable for the base class .. it mearly has the same data members in it, and can internally use the same functions ...

a class which uses "private" inheiritance is VERY VERY similar functionality wise to a class which just CONTAINS an instance of the base class object, with no inheiritance ... except that if it uses inheiritance, it can access "protected" as well as "public" members ... not just "public" members only

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by LukeSkyRunner
Is it "private" by default?
Yes. For structs, inheritance is "public" by default, but for classes it''s private.

Share this post


Link to post
Share on other sites