PDA

View Full Version : Ereditarietà C++


mason89
25-04-2013, 22:43
Ciao a tutti..ho un piccolo dubbio con l'ereditarietà in c++..
In pratica credo la classe Persona(classe base) e la classe Studente(derivata);
Se faccio l'ereditarietà public tutto ok, ma provando quella protected,non mi fa accedere ai metodi protected della classe base.Come mai?I dati protected nella classe base rimangono tali anche nella derivata,quindi come mai non riesco?Posto il codice della classe Persona.h
Mi affido a voi grazie.

#ifndef PERSONA_H_
#define PERSONA_H_

#include<iostream>
using namespace std;



class Persona
{
public:
Persona(string,string,int);
Persona(string,string,int,int);

void setNome(string);
void setCognome(string);
void setData(int);


string getNome()const;
string getCognome()const;
int getDataDiNascita()const;

protected:
int getCodiceFiscale(); // Spostato a protected per farlo ereditare con Ereditarietà protected!

string nome;
string cognome;
unsigned dataDiNascita;
int codiceFiscale;

private:
void setCodiceFiscale(int);

};

#endif

starfred
26-04-2013, 09:22
http://www.cplusplus.com/doc/tutorial/inheritance/

In particolare:

This public keyword after the colon ( : ) denotes the most accessible level the members inherited from the class that follows it (in this case CPolygon) will have. Since public is the most accessible level, by specifying this keyword the derived class will inherit all the members with the same levels they had in the base class.

If we specify a more restrictive access level like protected, all public members of the base class are inherited as protected in the derived class. Whereas if we specify the most restricting of all access levels: private, all the base class members are inherited as private.


Credo non si possa essere più chiari :)

mason89
26-04-2013, 21:47
Si ok pero i membri privati rimangono tali..quindi perche non riesco ad accedervi?

starfred
27-04-2013, 08:57
http://www.cplusplus.com/doc/tutorial/inheritance/


When a class inherits from another one, the members of the derived class can access the protected members inherited from the base class, but not its private members.