I am new at programming using c and having some troubles creating my constructors & objects. How can I access to my protected members like int p_iID in the Fahrzeug class? I have to access them for both of my objects seperately.
I would be so happy if you could help me out with this.
class Fahrzeug {
private:
protected:
string p_sName;
int p_iID;
double p_dMaxGeschwindigkeit;
double p_dGesamtStrecke;
double p_dGesamtZeit;
double p_dZeit;
public:
virtual void vAusgeben(Fahrzeug* pFahrzeug1,Fahrzeug* pFahrzeug2);
virtual void vKopf();
virtual void vSimulieren(Fahrzeug *pFahrzeug, Fahrzeug *pFahrzeug2);
class PKW;
class PKW: public Fahrzeug{
PKW(const int p_iMaxID, string p_sName, double p_dMaxGeschwindigkeit, double p_dGesamtStrecke) {
p_iID = p_iMaxID;
this->p_sName = p_sName;
this->p_dMaxGeschwindigkeit = (p_dMaxGeschwindigkeit < 0) ? 0 : p_dMaxGeschwindigkeit;
this->p_dGesamtStrecke = p_dGesamtStrecke;
}
void vAusgeben(PKW pkw1, PKW pkw2) {
cout << "\n";
PKW pkw1;
PKW pkw2;
pkw1.vKopf();
cout << setw(5) << left << pkw1.p_iID<< " " << setw(10) <<pkw1.p_sName << setw(8) << " " << setw(15) << showpoint << pkw1.p_dMaxGeschwindigkeit << setw(3) << " " << pkw1.p_dGesamtStrecke; //Here I have the issue with pkw1.p_sName
cout << "\n";
cout << setw(5) << left << pkw2.p_iID << " " << setw(10) << pkw2.p_sName << setw(8) << " " << setw(15) << showpoint << pkw2.p_dMaxGeschwindigkeit << setw(3) << " " << pkw2.p_dGesamtStrecke;
cout << "\n";
}
}
CodePudding user response:
void vAusgeben(PKW pkw1, PKW pkw2) {
You probably don't want to pass your PKW
objects by value (or expect object slicing). Pass const references instead:
void vAusgeben(const PKW& pkw1, const PKW& pkw2) {
Also, why are you shadowing your 2 parameters with these local variables?
PKW pkw1; // ???
PKW pkw2; // ???
CodePudding user response:
Aside from the issues raised in comments (and in another answer), there's a special rule for protected members that sometimes surprises people. An object of a derived type can access protected members of its base sub-object, but it can't access protected members of some other object. So:
struct B {
protected:
int i;
};
struct D : B {
void f(const B&);
};
void D::f(const B& b) {
i = 3; // okay, accessing my own protected member
b.i = 3; // no, access to protected member of different object not allowed
}
In the code in the question, the function PKW::vAusgeben
can access its own copies of p_sName
, p_dMaxGeschwindigkeit
, and p_dGesamtStrecke
, but it can't access pkw1.p_sName
, pkw1.p_dMaxGeschwindigkeit
, or pkw1.p_dGesamtStrecke
.