C++ classes question

Started by
5 comments, last by LukeSkyRunner 20 years, 1 month ago
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?
Advertisement
I believe if you use private or protected, you won''t be able to operate on the derived class using a pointer to the base class.

"When you die, if you get a choice between going to regular heaven or pie heaven, choose pie heaven. It might be a trick, but if it's not, mmmmmmm, boy."
How to Ask Questions the Smart Way.
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
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.
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
Ok, but what about declaring the derivation whitout those keywords? Is it "private" by default?
quote:Original post by LukeSkyRunner
Is it "private" by default?
Yes. For structs, inheritance is "public" by default, but for classes it''s private.

This topic is closed to new replies.

Advertisement