Avraam Mavridis
Avraam Mavridis

Reputation: 8920

The "Using" keyword to call base class constructor

I have the following base class

class Grammateas
{
 public:
 Grammateas(std::string name):_name(name){};
  virtual ~Grammateas(){};
 private:
  std::string _name;
};

and the following derived class

class Boithos final : public Grammateas
{
 public:
  //using Grammateas::Grammateas;
  Boithos(int hours):Grammateas("das"),_hours(hours){};
  virtual ~Boithos(){};
 private:
  int _hours;
};

I want to use the Base class constructor to create object like this

   Boithos Giorgakis(5); //works
   Boithos Giorgakis("something"); //Bug

I read that I can use the using keyword but when I try to use it like

   using Grammateas::Grammateas;

The compiler return a message

error: ‘Grammateas::Grammateas’ names constructor

Can you help me understand the using keyword with constructors?

Upvotes: 9

Views: 5923

Answers (1)

JoergB
JoergB

Reputation: 4463

Your code - with the using Grammateas::Grammateas; uncommented - should work. (But beware: the inherited constructor would leave _hours uninitialized.)

Inheriting constructors through using-declarations is a new feature in C++11. Maybe your compiler does not yet support this feature or has problems combining inherited constructors and other overloads. (If it accepts the final specifier, it appears to be set up correctly to compile C++11 in the first place.)

Upvotes: 10

Related Questions