Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
see we have the following class:
C++
class CText : public string
{
    CText();
    ~CText();
}

As you know, the class "string" in C++ has several version of constructors. Now I'd like my CText class to behave in such manners as follow:
C++
CText text("foo");
string str = "another foo :-)";
CText text2(str);
.
.
.

How do I define my constructors?
Posted
Updated 30-Oct-11 7:08am
v3

The same way you would define them for a new class; check the documentation for string to see what constructors exist, and provide the same.
 
Share this answer
 
Richard's answer is correct, but it is worth mentioning how to go about it.

For example, the string class has a constructor string(char *str).
Then you would define your class with the same constructor, and call the base class constructor as follows:
C++
class CText : public string
{
    CText(char *str) : string(str) { } //This calls the base class constructor
    //more constructors and other functions
}
 
Share this answer
 
If you can rely on C++11, a simple way can be
class CText: public string
{
public:
    template<class... T>
    CText(T&&... t) :string(forward<T>(t)...) 
    {}

    ...
};

Essentially the constructor is based on a varadic template (taking form 0 to whatever number of argument of whatever types) that are taking in term of r-value reference (think to it as a relaxed const&, that can also take and modify temporary values) and forwarded (in C++0x a && becomes a & when passed as argument: forward, just casts it back to &&) one-to-one to the base class.

As a result, until there is a constructor in string that takes certain parameters, They can be taken by the superclass as well.
 
Share this answer
 
v3
You need to define like this,
C++
CText(string str)
{
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900