• ### Announcements

#### Archived

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

# C++ classes question

## Recommended Posts

Watch the following code:
class derivada : public base
{
public:
{
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 on other sites
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.

##### 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 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 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 on other sites
Ok, but what about declaring the derivation whitout those keywords? Is it "private" by default?

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

• ### Forum Statistics

• Total Topics
627719
• Total Posts
2978790

• 9
• 21
• 14
• 12
• 42