Constructor problem

#include<iostream.h>
class A
{
protected:
int a,b;
public:
A()
{}
A(int x=0,int y)
{
a=x;b=y;
cout<<a<<b;
}
virtual void P(){}
};

class B:public A
{
private:
float p,q;
public:
B(int m,int n,float u,float v):
A(m,n),
p(u),q(v)
{}
B()
{p=q=0;}
void input(){}
virtual void P(float);
};
void B::P(float)
{}
main()
{A a1,*ptr;
B b1;
b1.input();
ptr=&a1;
ptr->P();
ptr=&b1;
ptr->P();

}

Above code show error while compilation stating that "Ambiguity between A() and A(int,int).
please let me why????

I believe your problem stems from the fact that if you assign a default value for an argument in a function, you must also assign default values for all the arguments that come after it in the list. You might consider the following:
1
2
3
4
5
6
7
8
A::A(int x, int y)
{
  a = x;
  b = y;
}

A::A(int y) : A(0, y)
{}
I'm assuming there is a cut and paste error in the above code since A(int x=0,int y) would yield a different compile error. Assuming OP meant A(int x=0, int y=0) then this constructor could be called with zero parameters, but so could the default one, so the compiler doesn't know which one to call.
hi jlamothe its me Sapath.
You told me that if i assign a default value for an argument in a function, i must also assign default values for all the arguments that come after it in the list.
ok thats true. But the code i posted will perform successfull compilation if i won't write A(). Instead only A(int x=0,int y).

that means the code
A(int x=0,int y)
{
a=x;b=y;
cout<<a<<b;
}
is correct. i need not assign default value for the later argument(in this case y).

then what is ur thought on that.
Please tell me.
I'm actually not well-versed enough in the C++ standard to tell you what that would do. It might be your compiler allowing you to do something not specified by the standard (can anyone else provide input on this?)

Like I said though, instead of assigning a default value to x, you can create a third constructor that only takes one input and automatically assigns x to zero (see lines 7-8 in the code snippet I provided).
Topic archived. No new replies allowed.