-13

Suppose that I have this piece of code:

class Vehicle {
   virtual const char* media() const = 0;
   virtual unsigned speed() const = 0;
} V, *PV;
class LandVehicle : public Vehicle {
   const char* media() const override{ return "Land";}
} L,  *PL;
class Train : public LandVehicle{
   virtual unsigned speed() const override {return 130;}
} T, *PT;

I have a few questions about it :D

1) LandVehicle doesn't implement speed(). is that an error and if so, what kind of error? or does it just make it an abstract class as well ?

2) is the keyword override in class LandVehicle in method media() used correctly? as a derived class from an abstract class is it really overriding the method?

3) same as 2 for override in Train's speed() method.

4) is Train a concrete class now?

5) is it necessary to add the keyword virtual in the declaration of LandVehicle's media() method?

6) if I add this method in Train class:

const char* media() const{ return "Just a train";}

does it hide LandVehicle's media() or does it override it ?

7) after adding the method in 6, can LandVehicle's media() be accessed in Train class?

3
  • 6
    There are too many questions, and for most of them you can find the answer quickly by testing it yourself.
    – Aracthor
    Commented Sep 5, 2016 at 12:27
  • Have you tried researching this yourself? What have you found and how has it failed to answer your questions? Commented Sep 5, 2016 at 12:30
  • 1
    I agree here. Quickly just writing the code/testing output is usually faster than even typing the code/question on stackoverflow.
    – Hayt
    Commented Sep 5, 2016 at 12:33

1 Answer 1

5

1.) Yes LandVehicle is still abstract. For a class to be instantiable you need to have implemented all pure virtual methods.

2.) Yes. override is a keyword for the compiler that it should override another method. If you e.g. change the signature in the base class. The compiler will give you an error here (if you don't use override it assumes it is a "new" method)

3.) same answer as 2. user override as often as possible if you override a method.

4.) Yes. All pure virtual (abstract) methods now have an implementation.

5.) No. The virtual only has to be added in the base class. It is not needed in derived classes for the same method.

6.) Yes. overrride is just a keyword for the compiler to check. It does not really s do the overriding or not (virtual is important for this). You can leave override out if the declaration but it's usually safer to use it always.

7.) Yes you can use LandVehicle::media()

Not the answer you're looking for? Browse other questions tagged or ask your own question.