0

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?

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by viki0077
0

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.