Let
class Customer
{
private:
long id;
string name;
public:
...
};
be part of a class definition.
What is wrong with the following constructors ?
Customer () { id(0); name(''X''); }
Customer () ( long n, const string& s) : id(s), name(n) { }


Does anyone know this?

Recommended Answers

All 3 Replies

What's a tremendous, innovative C++ syntax! ;)
Are you sure that it's DaniWeb members homework?

Syntax mainly:

Constructors use variable initializers and an additional code block
which happens after initialization.

i.e.

Customer() : id(0),name("X") 
{ // code block here }

the second version is wrong because you have an extra ().
(write long int please!).

The only other thing you are going to need is that initialization of c++ constructors is in order!

// WRONG CODE:
class A
{
    int a;
    int b;
 public:
    // THIS DOESN't WORK 
    A(const int I) : b(I), a(b+1) {}  
    // THIS WOULD WORK: 
//    A(const int I) : b(a+1),a(I) {}
};

Try the fragment above and you will find that a can be just about anything as b in uninitialized when b+1 is calculated. That because despite the order you write it in, a is initialized first as it is in the class first.

OK, thanks.

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.