Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How do I initialize a constructor of a separate class from the constructor of a class?

Basically what I am trying to achieve is to create a local (and private) instance of the class deltaKinematics in the class geneticAlgorithm

In the geneticAlgorithm.h file I have:

class DeltaKinematics; //class is defined in separate linked files

class GeneticAlgorithm {
  //private  
    DeltaKinematics deltaRobot;

public:

    GeneticAlgorithm(); //constructor

};

This is all fine, but when I go to declare the GeneticAlgorithm constructor, I can't work out how to construct the instance of DeltaKinematics

This is the geneticAlgorithm.cpp constructor:

GeneticAlgorithm::GeneticAlgorithm(){ //The error given on this line is "constructor for 'GeneticAlgorithm' must explicitly initialize the member 'deltaRobot' which does not have a default constructor"

    DeltaKinematics deltaRobot(100); //this clearly isn't doing the trick

    cout << "Genetic Algorithmic search class initiated \n";
}

How do I go about initializing that local instance?

like image 919
Zak Henry Avatar asked May 19 '11 07:05

Zak Henry


2 Answers

Member initializer list:

GeneticAlgorithm::GeneticAlgorithm() : deltaRobot(100) {
}
like image 151
Erik Avatar answered Sep 27 '22 22:09

Erik


GeneticAlgorithm::GeneticAlgorithm() : deltaRobot(100) {
    cout << "Genetic Algorithmic search class initiated \n";
}

Note the : after the constructor name: it is the beginning of the initialization sequence for the member data variables of the class. They appear as calls to their constructors, with the parameters you want to pass, and should be in the same order they're declared.

like image 29
littleadv Avatar answered Sep 27 '22 22:09

littleadv