简体   繁体   中英

Inheritance and polymorphism

So I'm learning about inheritance in my c++ class now and trying to put all the terminology to light. I understand the difference between protected and private. But when you make a function a friend isn't that the same thing as making it public?

The examples they are using to teach inheritance is shapes, so:

class shape{
   struct circle
   struct rectangle
   struct line
}

Something like that, what is the difference between saying

class circle: shape
class circle: public shape
class circle: private shape (don't actually know if this one is possible)

And finally, what does the keyword virtual mean/do/used for? Thank you

First and foremost you should pick up a good C++ book and read the concepts:

The Definitive C++ book and guide list


To get you started little brief about your Questions:

Your first example is an example of Composition not Inheritance .
Inheritance is IS A relationship.
Composition is HAS A relationship.

In the example, Circle IS A type of Shape .


class circle: shape 

is same as:

class circle: private shape 

For a class, Default Access specifier is Private by default. This is Private Inheritance . Class circle privately derives from class shape .

In Private Inheritance all the public and protected members of the Base class become Private members of the Derived class.

class circle: public shape 

Is Public Inheritance , Class circle publically derives from class shape .

In Public Inheritance the public members of Base class become Public members of Derived class and protected members of the Base class become Protected members of the Derived class.

This C++-Faq should be a good read for understanding the basics:
What are access specifiers? Should I inherit with private, protected or public?


But when you make a function a friend isn't that the same thing as making it public?
When you make a function as friend of an class, Access specifiers no longer apply to that function. That function can access, protected as well as private members of that class.But this is only limited to that function.


what does the keyword virtual mean/do/used for?
The keyword virtual is used to implement Dynamic/Run-Time Polymorphism .
It is an broad term to be explained as such, So it is upmost important that you read and understand the concept from an book. If you still face problems in understanding anything specific about it,Come back here and feel free to ask an Specific Question here.

是允许程序员创建新类的过程,该新类是现有类的特化,然后,新类称为现有类的Derived类,而现有类称为新创建的类的基础。

继承是指新类取代旧的现有类,而多态是指您将程序中的某个类引用为新引入类的基础。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM