Reputation: 93
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(){
x=0;
}
A(int i)
{
x=i;
}
int Get_x(){
return x;
}
};
class B{
private:
A objA(1);
public:
objA.Get_x();
};
This is my code and it has two classes i.e A and B ..First class runs fine but in class B ..compiler gives the syntax error in the declaration of objB.....But as far as i know it should be correct ...so plz help ....thanks
Upvotes: 0
Views: 52
Reputation: 3649
The compiler is trying to interpret A objA(1)
as a function declaration, which is wrong. You may declare objA as A objA = A(1);
(please note that thi is a C++11 feature, you may need to enable it before).
Also, I don't really know what objA.Get_x()
should do, but this is also wrong, you can't just access a member outside of a function. Probably, you meant this:
int Get_x() {
return objA.Get_x();
}
Upvotes: 0
Reputation: 227400
This initialization is invalid for a data member:
A objA(1);
You need
A objA{1};
or
A objA = A(1);
Besides that, this kind of statement can only happen inside of a function:
objA.Get_x();
Upvotes: 1