while creating object of a class in another class having only parameterized Ctor "error: x is not a type"

StackOverflow https://stackoverflow.com/questions/17463532

  •  02-06-2022
  •  | 
  •  

Domanda

When I try to create an object of class A having only parametrized Constructor in class B, I get following errors:

A ob(5); error: expected identifier before numeric constant  
A ob(x); error: x is not a type 

class A {
    public:
    int z;
    A(int y){z = y;}
};
class B {
    public:
    int x;
    A ob(5); or A ob(x);//This line is creating a problem
};

I searched for the same and got that we can solve this problem by writing

A ob;
B():ob(5);
OR
int x;
A ob;
B():ob(x);   //here x will be uninitialized though

But I am thinking why it was giving error in the prior case. Can someone explain in detail. Thanks.

È stato utile?

Soluzione

You cannot assign default value to class member in C++. You need to define constructor.

class A {
    public:
    int z;
    A(int y){z = y;}
};
class B {
    public:
    int x;
    A ob; //
    B() : x(5), ob(x) {}
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top