CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Apr 2011
    Posts
    10

    Initializing base class part from derived object using copy constructor

    class Base
    {
    char * ptr;

    public:
    Base(){}
    Base(char * str)
    {
    ptr = new char[strlen(str)];
    strcpy(ptr,str);
    }

    };

    class Derived : public Base
    {
    char * ptr_s;
    public:

    Derived(char * str1,char * str2):Base(str2)
    {
    ptr_s = new char[strlen(str1)];
    strcpy(ptr_s,str1);
    }
    Derived(const Derived & sec)//:Base(sec.ptr)
    {
    this->ptr_s = new char[strlen(sec.ptr_s)];
    strcpy(this->ptr_s,sec.ptr_s);

    }

    };


    int _tmain(int argc, _TCHAR* argv[])
    {

    Derived Obj1("sunil","singh");

    Derived Obj2 = Obj1;

    return 0;
    }


    Obj1 is a derived class object where base class char pointer is initialized with "singh" and
    derived class char pointer is initilized with "sunil". I want to create Obj2 out of Obj1. Separate memory should be created for
    Obj2 char pointer (base part and derived part as well) and that should be initialized with the strings contained in Obj1.
    Here the problem is: Derived class part can be initialized with copy constructor. How to initialize the base class char poniter of Obj2 with the base class part of Obj1. char pointers in
    both the classes are private.

    I tried using initializer list but could not succeed.

    Is there some proper way to do this?

    Thanks for any help or suggestion in advance.

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Initializing base class part from derived object using copy constructor

    First of all, when posting code you should embed it in code tags to preserve the indentation [code]Paste your code here[/code] and making the code readable.

    Second why don't you use std::string instead of character arrays? That way you don't have to suffer from out-of-bounds bugs and memory leaks (as you currently are).
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Initializing base class part from derived object using copy constructor

    Please post your code in [code][/code] bbcode tags. Now:
    • You're manually managing the memory, but you did not define the copy constructor, copy assignment operator and destructor for Base.
    • Your use of strcpy leads to an array out of bounds write because you used strlen, but forgot to account for the null character.
    • I don't see why you don't have const char* parameters instead (but see below about std::string).
    • Your base class has a public destructor, but it was not declared virtual. This would lead to undefined behaviour if an attempt was made to destroy a Derived class object from a base class pointer.


    If you had done it right, you could then just write:
    Code:
    Derived(const Derived & sec) : Base(sec)
    {
        // ...
    Actually, you can easily do this right by using std::string members instead of manually managing memory.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Initializing base class part from derived object using copy constructor

    Quote Originally Posted by ksingh.sunil@gmail.com View Post
    Obj1 is a derived class object where base class char pointer is initialized with "singh" and derived class char pointer is initilized with "sunil". I want to create Obj2 out of Obj1. Separate memory should be created for
    Obj2 char pointer (base part and derived part as well) and that should be initialized with the strings contained in Obj1.
    Here the problem is: Derived class part can be initialized with copy constructor. How to initialize the base class char poniter of Obj2 with the base class part of Obj1. char pointers in
    both the classes are private.
    There is so much wrong with your code, that I might as well show you how to do this using std::string:
    Code:
    #include <string>
    
    class Base
    {
       std::string ptr;
       public:
         virtual ~Base() { }
         Base(){}
         Base(const std::string& str) : ptr(str) { }
    };
    
    class Derived : public Base
    {
        std::string ptr_s;
        public:
           Derived(const std::string& str1, const std::string& str2):Base(str2), ptr_s(str1) { }
    };
    
    int main()
    {
        Derived Obj1("sunil","singh");
        Derived Obj2 = Obj1;
        return 0;
    }
    That same code you see above does the same thing you're trying to do.

    The code above is safer, shorter, easier to maintain, works all the time, no memory allocation/deallocation issues, the copy constructor and assignment operators work, no destructor is necessary, etc, etc.

    Thanks for any help or suggestion in advance.
    Here is some help:

    http://www.parashift.com/c++-faq-lit....html#faq-34.1

    As to your attempt you are:

    1) You're writing beyond the bounds of the memory by calling strcpy() and not ensuring you have enough room.

    2) Your class lacked a virtual destructor. This in itself isn't going to cause a problem, unless you start to use polymorphism and you are using base class pointers that actually point to derived objects.

    3) Your class fails if NULL is passed as one of the arguments to the constructor:
    Code:
    Derived d(NULL, NULL);
    That line of code will lead to undefined behaviour, since strlen() is not guaranteed to check for NULL pointers.

    4) You did not implement an assignment operator to go along with the copy constructor.

    5) You did not implement a destructor, therefore your code has memory leaks.

    And there are probably more to that piece of code you tried to write. So do you now see the power of using a string class, in this case, std::string, instead of trying to do this on your own?

    And even if you did want to do this on your own, I suggest you write a string class first. Then you use your home-made string class similar to the code I wrote.

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Apr 2011
    Posts
    10

    Re: Initializing base class part from derived object using copy constructor

    Thanks for the help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured