views:

89

answers:

7

Hi,

The following code doesn't work:

class String{
public:
    char* str;
    int* counter;

    String(){
        str = NULL;
        counter = new int;
        *counter = 1;
    };
    String(const char* str1){
        String();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
    };


 };

I've changed the call to the empty constructor and replaced it with its internals, and now the following code works:

class String{
public:
    char* str;
    int* counter;

    String(){
        str = NULL;
        counter = new int;
        *counter = 1;
    };
    String(const char* str1){
        //String();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
        counter = new int;
        *counter = 1;
    };

Can you please suggest why?

Thanks, Li.

+2  A: 

In the current C++, constructors cannot call each other. That's called "chaining constructors", or "delegating constructors" and is supported by the new C++0x standard but with a different syntax than the one you are using.

Off-topic, why do you use a pointer to int for the counter?

Nemanja Trifunovic
+2  A: 

It seems to me you are trying to invoke a constructor from another constructor of the same class, like you would in C# for example. Unfortunately you cannot do this in C++ (at least no easy way I know of). You need to either have a private method or duplicate the code.

Skurmedel
A: 
  • why is the counter a pointer ?

What does not work ? compilation error ?

Probably calling the constructor inside another is not well supported on your compiler ?

what platform ?

Max
+3  A: 

"Doesn't work" is not a good description of the problem. But you apparently tried to invoke a constructor from another one. That's called constructor delegation and is not (yet) supported by C++.

BTW, a class like this should get a user-defined copy constructor, assignment operator and destructor.

sellibitze
+1: For copy ctor, assignment and destructor
Tony
+1  A: 

Calling String(); actually creates a temporary object and then throws it away again. It won't call the other constructor.

DanDan
+1  A: 

The call 'String();' creates an unnamed temporary object of type String that is destroyed immediately. The second code snippet is fine.

However you should really relook at the members of your class. Use std::string instead of raw char pointer. Also int *counter does not look very intuitive

Chubsdad
+1  A: 

You are allowed to do something like this:

class String{

public:
    char* str;
    int* counter;

private:
    void initialize() {
        str = NULL;
        counter = new int;
        *counter = 1;
    }
public: 
    String(){
        initialize();
    };
    String(const char* str1){
        initialize();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
    };


 };
TokenMacGuy