Quantcast
Channel: What are the rules for calling the base class constructor? - Stack Overflow
Viewing all articles
Browse latest Browse all 22

Answer by Markus Dutschke for What are the rules for calling the base class constructor?

$
0
0

If you simply want to pass all constructor arguments to the base-class (=parent), here is a minimal example.

This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class std::string.

Code

Live-Version

#include <iostream>#include <string>class ChildString: public std::string{    public:        template<typename... Args>        ChildString(Args... args): std::string(args...)        {            std::cout << "\tConstructor call ChildString(nArgs="<< sizeof...(Args) << "): " << *this<< std::endl;        }};int main(){    std::cout << "Check out:" << std::endl;    std::cout << "\thttp://www.cplusplus.com/reference/string/string/string/" << std::endl;    std::cout << "for available string constructors" << std::endl;    std::cout << std::endl;    std::cout << "Initialization:" << std::endl;    ChildString cs1 ("copy (2)");    char char_arr[] = "from c-string (4)";    ChildString cs2 (char_arr);    std::string str = "substring (3)";    ChildString cs3 (str, 0, str.length());    std::cout << std::endl;    std::cout << "Usage:" << std::endl;    std::cout << "\tcs1: " << cs1 << std::endl;    std::cout << "\tcs2: " << cs2 << std::endl;    std::cout << "\tcs3: " << cs3 << std::endl;    return 0;}

Output

Check out:    http://www.cplusplus.com/reference/string/string/string/for available string constructorsInitialization:    Constructor call ChildString(nArgs=1): copy (2)    Constructor call ChildString(nArgs=1): from c-string (4)    Constructor call ChildString(nArgs=3): substring (3)Usage:    cs1: copy (2)    cs2: from c-string (4)    cs3: substring (3)

Update: Using Variadic Templates

To generalize to n arguments and simplify

        template <class C>        ChildString(C arg): std::string(arg)        {            std::cout << "\tConstructor call ChildString(C arg): " << *this << std::endl;        }        template <class C1, class C2>        ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)        {            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;        }        template <class C1, class C2, class C3>        ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)        {            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;        }

to

template<typename... Args>        ChildString(Args... args): std::string(args...)        {            std::cout << "\tConstructor call ChildString(nArgs="<< sizeof...(Args) << "): " << *this<< std::endl;        }

Viewing all articles
Browse latest Browse all 22

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>