Saturday, January 11, 2014

Chapter:09 Delegating Constructors

Delegating constructor is a mechanism where one constructor body can delegate its work to other constructor. This mechanism supports the reuse of already implemented functions. Normally we should write one constructor in more generic sense. Once we define such constructor ,we can make use of this  for defining other constructor. This is  known as delegation mechanism.


Prior to existence of this concept, we normally had to write one common function and call it from almost all the place inside  constructor body. However ideally we should not try to 'call/use' any member functions inside the constructor as objects may not be in valid state until they call constructor successful. In a way in class initialize, 'default/delete' and delegating constructor are very much similar and normally gets used at one place.


All delegating constructor would be called and used outside of the constructor body. If somone tries to call it from the inner body of constructor,ill effects may happen in your program. As I have mentioned that ideally inside constructor body we should not use any other member  functions as objects  is yet to be created. This holds true for even other constructor and hence it should not be used inside the body of any of your constructor. This is key in this concept.



//Code Begins

#include<iostream>
#include<cstring>
#include<algorithm>

class x {
public:
    x(int len): length(len) {std::fill(ptr,ptr+length,'\0');}

    x(): x{1} {}

    x(char* n):x{strlen(n)+1}{strncpy(ptr,n,length);}

    ~x() {delete[] ptr;}

    void display(void) {std::cout<<ptr<<std::endl;}
private:
    int length{20};
    char* ptr{new char[length]};
};


void learn_delegating_constructor(void)
{
    x o_a;
    o_a.display();

    x o_b(10);
    o_b.display();

    char* input{"Mantosh"};
    x  o_c(input);
    o_c.display();
}

int main(int argc, const char* argv[]) {
    learn_delegating_constructor();
    return 0;
}

//Code Ends



When I run the above program, I get the following output.



//Console Output Begins
$ ./test
Mantosh
//Console Output Ends

No comments:

Post a Comment