What am I doing wrong?
class Vehiculo{
virtual string toString();
}
In class
the visibility of the elements is, by default, private. This means that only members of Vehiculo
can access. To change this visibility you must expressly indicate:
class Vehiculo{
public: // <<--- Visibilidad publica
virtual string toString();
}
And the same thing happens with inheritances ... if you use class
the inheritances will be private unless otherwise indicated ... What does it mean that an inheritance is private?
It is a bit more convoluted to explain but simplifying a bit could be said that the inheritance will not be visible ... as if it did not exist for anyone except for the class that receives the inheritance.
At the moment to simplify your life try not to use private inheritance:
class Auto : public Vehiculo {
// ^^^^^^ herencia publica
string toString();
}
Note: By the way, the statements of a class must end always with a semicolon:
class Vehiculo{
public:
virtual string toString();
}; // <<--- Importante!!!
may I have to use override
?
override
is a reserved word that is available from the C ++ 11 standard and only serves for the compiler to help us detect inconsistencies when overwriting functions. When you mark a function as override
, all you do is tell the compiler to verify the following:
- That in some parent class there is a function with exactly the same statement
- That the function of the parent class is marked as
virtual
That is:
struct Base
{
virtual void Func1(int) const;
virtual void Func2(int) const;
virtual void Func3(int) const;
virtual int Func4(int) const;
void Func5();
};
struct Derivada : Base
{
void Func1(int) const override; // OK
void Func2(int) override; // ERROR: falta const
void Func3() const override; // ERROR: falta el argumento int
void Func4(int) const override; // ERROR: el tipo de retorno no es el mismo
void Func5() override; // ERROR: Base::Func5 no es virtual
};
If in the previous example we had not used override
the compiler would not notify us of those errors and the final program, very surely, would not work as we expect.
I'm also interested in accessing toString
of Vehiculo
You can force the call to the function of the parent class with Vehiculo::
:
string Auto::toString() {
return "esto es un auto\n" + Vehiculo::toString();
}