i have a problem instantiating an object, to demostrate that problem i created three files named body.cpp, head.h, head2.h

the content of the files are as follows:
body.cpp:

#include "head.h"

class2::class2()
{
  myClass(5);
}

int main()
{
  class2 myFinalClass();
  return 0;
}

head.h:

#include "head2.h"

class class2
{
  public:
    class1 myClass;
    class2();
  
};

head2.h:

class class1
{
  public:
    int b;
  class1(int a)
  {
    b = a;
  }
};

the problem is when i compile this compiler gives an error saying :
The data member "myClass" cannot be initialized because there is no corresponding default constructor.

what should i do? i need to declare an object on the header file of my class file then initialize that object in my constructor of the class.

Thanks

Rashakil Fol commented: You always ask questions very clearly. +8

that's funny...:P ...

//....
myClass.b = 5; 
//....

You can't call a constructor after the object is created. By the time you get to class2's constructor body, myClass will already have been constructed. However, because class1 doesn't have a default constructor, this won't compile because there's no constructor to call. You can fix it by using an initialization list:

class2::class2(): myClass(5) {}

Also note that class2 myFinalClass(); is probably not doing what you think it's doing. It's actually a prototype for a function taking no parameters and returning an object of class2.

commented: i respect her knowledge so much +2

Thank you so much Narue, i searched google very hard before posting this thread and i couldnt find any useful information. Sometimes it is hard to find information if you dont know what you are looking for, what keywords would you type in google in order to find useful search results for this problem? I already understood it, i am just asking to improve my searching ability.

>what keywords would you type in google in order
>to find useful search results for this problem?
I'd start by checking the C++ FAQ Lite articles on constructors. For a more specific search, you can use keywords directly from the error. "C++ default constructor initialized", for example.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.