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:

#include "head.h"


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


#include "head2.h"

class class2
    class1 myClass;


class class1
    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.


You always ask questions very clearly.

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.

i respect her knowledge so much

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.

This question has already been answered. Start a new discussion instead.