1

I have a class Grandparent which is provided by a library. I’d like to define an interface for subclasses of Grandparent, so I created an abstract subclass called Parent:

class Grandparent {
    public:
        Grandparent(const char*, const char*);
};

class Parent : public Grandparent {
    public:
        virtual int DoSomething() = 0;
};

The constructor for Grandparent takes two arguments. I’d like my child class, Child, to also have a constructor with two arguments, and just pass these to the constructor for Grandparent… something like

class Child : public Parent {
    public:
        Child(const char *string1, const char *string2)
        : Grandparent(string1, string2)
        {}

        virtual int DoSomething() { return 5; }
};

Of course, Child’s constructor can’t call its grandparent class’s constructor, only its parent class’s constructor. But since Parent can’t have a constructor, how can I pass these values to the grandparent’s constructor?

bdesham
  • 15,430
  • 13
  • 79
  • 123

2 Answers2

3

Parent can certainly have a constructor. It must, if it's going to call the Grandparent constructor with any parameters.

There's nothing forbidding abstract classes from having constructors, destructors, or any other kind of member function. It can even have member variables.

Simply add the constructor to Parent. In Child, you'll call the Parent constructor; you can't "skip a generation" with constructor calls.

class Parent: public Grandparent
{
public:
  Parent(char const* string1, char const* string2):
    Grandparent(string1, string2)
  { }
  virtual int DoSomething() = 0;
};
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • For some reason I thought that abstract classes couldn’t have constructors. Of course your solution worked great. Thanks! – bdesham Feb 28 '12 at 05:56
  • Perhaps you're thinking of *interfaces* in some other language, like Java, C#, or Delphi. C++ doesn't have a separate interface type. – Rob Kennedy Feb 28 '12 at 06:03
  • Yes, I’m coming from Objective-C, and I’m still working out the differences between interfaces and abstract base classes. – bdesham Feb 28 '12 at 18:55
2

If you want something else than the default constructor for Parent, you need to provide it.

Check out this question about inheriting constructors

Also, see this example of an abstract class

Community
  • 1
  • 1
Steinbitglis
  • 2,482
  • 2
  • 27
  • 40