0

In the following code

class someClassB;

class someClassA
{
public:
    someClassA(int x, int y);
private:
    someClassB* B;
};

class someClassB
{
public:
    someClassB(int x, int y);
private:
    int x;
    int y;
    someClassA A;
};

someClassA::someClassA(int i, int j) 
{
    B->x = i;
    B->y = j;
}

someClassB::someClassB(int i, int j)
{
    x = i;
    y = j;
    A = new someClassA(i, j);
}

why do I get an error saying 'Constructor for 'someClassB' must explicitly initialize the member 'A' which does not have a default constructor'? Am I not initializing 'A' in someClassB's constructor?

3 Answers3

5

someClassA does not have a default constructor. Currently, someClassB needs to default initialize it, resulting in the compilation error you quote. .You need to explicitly initialize the someClassA data member using one of its available constructors. For example,

someClassB::someClassB(int i, int j) : x(i), y(j), A(i, j)
{
}

Here, x and y are also initialized in the constructor initialization list, as opposed to default initialized and then assigned values to, as in your code.

Also note that, in general, this makes no sense in C++:

A = new someClassA(i, j);

new returns a pointer.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
4

Given that you are using A with new, I suspect you meant to declare it as a pointer:

someClassA* A;

If not, then you need to initialize it in someClassB's initializer list.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0
someClassA::someClassA(int i, int j) 
{
    B->x = i;
    B->y = j;
}

create a new instance of class someClassB as B is a pointer and you didn't allocated memory for this.

A = new someClassA(i, j);

A is not a pointer this is an instance of someClassA

rajenpandit
  • 1,265
  • 1
  • 15
  • 21