class complex
{
  int real;
  int imag;
public:
  complex(){}//why default constructor is always needed
  complex(int a,int b){real = a;imag = b;}// why can't we define only this constructor 
  ~complex(){}
};

If you don't define any constructors, the compiler will generate a default constructor for you (or make it appear as if one was generated). However, the instant you define an explicit constructor, that default constructor is not longer created.

As for why your class needs an explicit default constructor, clearly you're using the class in ways that require a zero argument constructor, yet you've also defined a two argument constructor.

whenever we define an explicit constructor , is it necessary to define a default constructor as well?
because in one of my code i simply defined an explicit constructor without defining the default one,and i found an error

whenever we define an explicit constructor , is it necessary to define a default constructor as well?

No, it's not necessary. However, the instant you use your class in a way that requires a default constructor, it becomes necessary unless one of your explicit constructors can be used as a default constructor:

class foo {
public:
    foo(int arg=0); // This can be used as a default constructor
};

because in one of my code i simply defined an explicit constructor without defining the default one,and i found an error

You're using the class in a way that requires a default constructor. I can't give you specifics because you didn't post the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.