user5749114
user5749114

Reputation:

Constructor taking char pointer

This is going to be a basic question, but hope someone can help me..

I have function like this;

void createInstance()
{
   MyClass m_Class;
   m_Class(25, "Roger")(32, "Pete")(56, "Haley")(89, "Tom");
}

Now in the MyClass:

class MyClass 
{
    MyClass();
    MyClass(int, const char&); // Gets ERROR here...
};

I want to write a constructor in MyClass that can take line #2 from createInstance function.

How can i do that?

Upvotes: 1

Views: 522

Answers (2)

Nir Friedman
Nir Friedman

Reputation: 17704

Obligatory: why do you want to do this, and what do you want it to do? In terms of making it compile, you have to understand that the way it's written, your object is already constructed. The second line is not a constructor call at all, but calling operator() on your object, which you haven't defined. Do you want to create multiple objects, or do you want to be able to flexibly pass multiple of these int, string pairs to your object post construction? If you want to do the latter, you can do this:

class MyClass 
{
    MyClass();

    MyClass& operator()(int x, const char* str) {
        // Do stuff with x and str
        return *this;
    }
};

What's clever about this is that the operator() returns a reference to the object itself, which of course has the operator(), so you can call it again, which again returns a reference to the object, and so on. Here's a working example: http://coliru.stacked-crooked.com/a/a0873be09770afd2.

Upvotes: 2

Jacob Seleznev
Jacob Seleznev

Reputation: 8131

Like this:

MyClass(int, const char*);

Upvotes: 0

Related Questions