Leo Fang
Leo Fang

Reputation: 852

How to initialize a vector of base-class constructors?

I have a base_class which has no default constructor, and I'd like to define a vector version of it (called derived_class). I know I should initialize the base_class constructor in my derived_class constructor, but the code below which attempts to initialize a vector with size dim and base_class(0,1) in each row cannot be compiled (it complains error: constructor for 'derived_class' must explicitly initialize the base class 'base_class' which does not have a default constructor), unless I add a default constructor (the commented line) to base_class. Do I miss or misunderstand something? Is there a way to make it work without defining the default base_class constructor?

#include <iostream>
#include <vector>

class base_class
{
   public:
      //base_class(){};
      base_class(double a, double b){a_=a; b_=b;}
   private:
      double a_, b_;
};

class derived_class : public base_class
{
   public:
      derived_class(int dim): vector_object(dim, base_class(0,1)){};
      std::vector<base_class> print_vector_object() {return vector_object;}
   private:
      std::vector<base_class> vector_object;
};


int main()
{
  int dim = 3;
  derived_class abc(3);
  std::cout << abc.print_vector_object().size() << std::endl;
  return 0;
}

UPDATE: I understand that I can totally avoid inheritance here in this simple case, but please assume that I do need inheritance for actual practice, thanks.

UPDATE2: As hinted by @vishal, if the constructor of derived_class is written as

derived_class(int dim) : base_class(0,0), vector_object(dim, base_class(0,1)) {};

The code can pass compiler. But I still don't understand why I have to initialize in this way...

Upvotes: 1

Views: 1925

Answers (4)

Francis Cugler
Francis Cugler

Reputation: 7915

I have rewritten your class slightly

#include <iostream>
#include <vector>

class base_class {
private:
    double a_, b_;

public:
    //base_class(){};
    base_class(double a, double b ) : a_(a), b_(b) {}
    virtual ~base_class();
};

class derived_class : public base_class {
private:
    std::vector<base_class> vector_object;

public:
    explicit derived_class( int dim ) : base_class( 0, 1 ) {
        vector_object.push_back( static_cast<base_class>( *this ) );
    }

    ~derived_class();

    std::vector<base_class> get_vector_object() const { return vector_object; }
};

int main() {

    int dim = 3;
    derived_class abc(3);
    std::cout << abc.get_vector_object().size() << std::endl;
    return 0;
}

This builds and compiles correctly. There were a few changes I made: I used the constructors member initializer list where applicable, I've added a virtual destructor to your base class; any time you inherit from a base class should have a virtual destructor, I moved all private member variables to the top of the class instead of at the bottom, I prefixed the derived_class constructor with the explicit keyword since you only have 1 parameter passed into it, I've changed the derived_class constructor to use the base_class constructor within its member's initialization list and I populated its member variable vector within the constructor using the push_back() method and statically casting the dereferenced this pointer to a base_class type, and I've also changed your print_vector_object method to just get_vector_object since it doesn't print anything and only return the member vector from the class. I also declared this method as const so that it doesn't change the class since you are only retrieving it. The only question that I have is what does the int parameter in the derived_class do? It is not used in any place and you have no member variable to store it.

This section of your derived class here

public: derived_class(int dim): vector_object(dim, base_class(0,1)){};

where you declare your constructor is not making any sense to me.

It appears that you are trying to use the member initialization list to populate your vector member variable by passing in your derived class's passed in parameter and calling the constructor to your base class with values of {0,1}. This will not work as you would expect. You first have to construct your Base Class object which is a sub object to this derived class than within your constructor's function scope you can then populate your member vector.

What you have will cause a problem because you do not have a default constructor supplied that is available to try and construct your derived type. Since from what I can gather on what you have shown and what it appears what you are trying to do it seems that you want to have the base_class initialized to {0,1} when the derived constructor is called; if this is the case you can just call your implemented constructor for the base_class with {0,1} passed in its constructor while your derived type tries to be constructed. This will allow the derived_class to be constructed properly since the base_class has been constructed. Now that you are able to begin construction of your derived type it looks like you want to save the constructed base_class into your derived types vector member variable. This is why I do this within the constructor and not within the initialization list and I push_back an instance of the derived type that is statically casted back to a base type using the dereferenced this pointer. Also when I set a break point in the main function where you are trying to print its size and I look at derived_class's member variable it is populated with 1 object that has the values of a = 0 and b = 1. To be able to print these you would have to add public get methods to return each variable. Also if the int parameter in your derived class is not needed you can remove it along with the explicit keyword. You could also implement a second constructor for the derived type that takes in two doubles just as the base does and pass those parameters from the derived_class constructor to the base_class constructor like this:

public:
    derived_class( double a, double b ) : base_class( a, b ) {
        vector_object.push_back( static_cast<base_class>( *this ) );
    }

I will demonstrate a simple example of a base and two derived classes where the first instance will have to set the values upon construction while the second will have to use its own constructor where there is no default constructor that is defined in the base class.

class Base {
private:
    double x_, y_, z_;

public:
    Base( double x, double y, double z );
    virtual ~Base();  
};

Base::Base() : 
x_( x ), y_( x ), z_( z ) {
}

Base::~Base() {
}

class DerivedA : public Base {
private:
    int value_;

public:
    explicit DerivedA( int value );
    ~DerivedA();
};

// In This Case A Must Set The Values In The Constructor Itself: I'll Just
// Set Them To (0, 0, 0) To Keep It Simple
DerivedA::DerivedA( int value ) :
Base( 0, 0, 0 ),
value_( value ) {
}

DerivedA::~DerivedA() {
}

class DerivedB : public Base {
private:
    int value_;

public:
    DerivedB( int value, double x, double y, double z );
    ~DerivedB();
};

// In This Case B Doesn't Have To Know What Is Needed To Construct Base
// Since Its Constructor Expects Values From Its Caller And They Can
// Be Passed Off To The Base Class Constructor
DerivedB::DerivedB( int value, double x, double y, double z ) :
Base( x, y, z ),
value_( value ) {
}

DerivedB::~DerivedB() {
}    

Let me know if this helps you out!

Upvotes: 0

cdonat
cdonat

Reputation: 2822

Are you sure, that a derived_class-object is a base_class-object and holds a vector of base_class-objects?

I assume, you actually only want a vector of base_class-objects. If that is true, don't derive derived_class from base_class. Actually that is where your compiler message comes from. It tells you, that you'll have to initialize the base_class aspect of your derived_class-object.

So here is my solution for you (beware, code is untested and will probably contain some bugs):

#include <iostream>
#include <vector>

class base_class
{
   public:
      // c++11 allows you to explicitly delete the default constructor.
      base_class() = delete;
      base_class(double a, double b):
          a_{a}, b_{b} // <- prefer initializers over constructor body
      {};
   private:
      double a_;
      double b_;
};

class derived_class // <- this name is wrong now of course; change it.
{
   public:
      derived_class(int dim):
          // better initialize doubles with float syntax, not int.
          vector_object{dim, base_class{0.0, 1.0}}
      {};

      // Note: this will copy the whole vector on return.
      // are you sure, that is what you really want?
      auto print_vector_object() -> std::vector<base_class> {
          return vector_object;
      };
   private:
      std::vector<base_class> vector_object;
};


int main(int, char**)
{
  // int dim = 3; <- this is useless, you never use dim.
  auto abc = derived_class{3};
  std::cout << abc.print_vector_object().size() << std::endl;
  return 0;
}

Note: my code is meant to be C++11.

Upvotes: 0

Christian Hackl
Christian Hackl

Reputation: 27538

Your vector_object is a red herring and has nothing to do with the problem, as you can verify with the following piece of code which will also make the compiler complain about the missing base_class default constructor:

class derived_class : public base_class
{
   public:
      derived_class(int dim) {} // error, tries to use `base_class` default constructor,
                                // but there is none...
};

You must either provide a default constructor or use a non-default one. In every instance of derived_class, there is a base_class sub-object, and the sub-object has to be created somehow.

One possible source of misunderstanding is the fact that objects in an inheritance hierarchy are initialized from top to bottom (base to derived). It may not seem logical at first sight, but by the time the derived_class constructor runs, the base_class sub-object must already exist. If the compiler cannot provide for this, then you get an error.

So even though the derived_class constructor specifies how the base_class sub-object is created, the actual creation of the sub-object happens before the creation of the derived_class part.

You are asking the following:

shouldn't the base_class object be initialized in my code?

Your code must initialize it, but it does not. You don't initialize it anywhere, and the default initialization does not work because the base class does not have a default constructor.

Sometimes, it helps to consider inheritance a special form of composition (there are indeed some striking similarities). The following piece of code suffers from the same problem as the one in your posting:

class base_class
{
   public:
      //base_class(){};
      base_class(double a, double b){a_=a; b_=b;}
   private:
      double a_, b_;
};

class derived_class // <--- no inheritance
{
   public:
      base_class my_base; // <--- member variable

      derived_class(int dim) {};
};

Would you still think that derived_class initializes the base_class object?


Another possible source of misunderstanding is the aforementioned red herring. You are saying:

I just don't understand why I cannot initialize it in a vector (...).

Because the vector member variable has nothing to do with the base_class sub-object, or with the public base_class member variable in my other example. There is no magical relationship between a vector member variable and anything else.

Taking your original piece of code again, a complete derived_class object can be pictured as follows in memory:

+-------------------+
| +---------------+ |
| |     double    | | <--- `base_class` sub-object
| |     double    | |        
| +---------------+ |
+-------------------+              +--------+--------+--------+....
|     std::vector ---------------> | double | double | double |
+-------------------+              | double | double | double |
                                   +--------+--------+--------+....
                                        ^
                                        |
                                        |
                                  a lot of other
                                `base_class` objects 

The base_class objects managed by the vector are completely unrelated to the base_class sub-object that owes its existence to class inheritance.

(The diagram is a little over-simplified, because a std::vector normally also stores some internal book-keeping data, but that's irrelevant to this discussion.)


However, your code does not make a convincing case for inheritance anyway. So why do you inherit in the first place? You may as well do like this:

#include <iostream>
#include <vector>

class base_class
{
   public:
      //base_class(){};
      base_class(double a, double b){a_=a; b_=b;}
   private:
      double a_, b_;
};

class derived_class // <--- no more inheritance (and thus wrong class name)
{
   public:
      derived_class(int dim) : vector_object(dim, base_class(0,1)){};
      std::vector<base_class> print_vector_object() {return vector_object;}
   private:
      std::vector<base_class> vector_object;
};


int main()
{
  int dim = 3;
  derived_class abc(3);
  std::cout << abc.print_vector_object().size() << std::endl;
  return 0;
}

Upvotes: 1

vishal
vishal

Reputation: 2391

Well, since you do not want to create default constructor in base class, you can call base constructor by:

derived_class(double a, double b, int dim) : base_class(a,b), vector_object(dim, base_class(0,1)) {};

Upvotes: 6

Related Questions