Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I′m trying to instantiate an object which has no default constructor so it can be referenced from any methods inside the class. I declared it in my header file, but the compiler says that the constructor for the class creating it must explicitly initialize the member, and I can′t figure out how to do that.

Really appreciate your answers, thank you in advance!

The snippet:

MyClass.h

include "MyOtherClass.h"

class myClass {

    private:
        MyOtherClass myObject;

    public:
        MyClass();
        ~MyClass();
        void myMethod();

}

MyClass.cpp

include "MyClass.h"

MyClass::MyClass() {

   MyOtherClass myObject (60);
   myObject.doSomething();

}

MyClass::myMethod() {

    myObject.doSomething();

}

MyOtherClass.h

class MyOtherClass {

   private:
      int aNumber;

   public:
      MyOtherClass (int someNumber);
      ~MyOtherClass();
      void doSomething();
}

MyOtherClass.cpp

include "MyOtherClass.h"

MyOtherClass::MyOtherClass (int someNumber) {
   aNumber = someNumber;
}

void MyOtherClass::doSomething () {
    std::cout << aNumber;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
822 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are almost there. When you create an object in C++, by default it runs the default constructor on all of its objects. You can tell the language which constructor to use by this:

MyClass::MyClass() : myObject(60){

    myObject.doSomething();

}

That way it doesn't try to find the default constructor and calls which one you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...