1

I'm still a bit shaky about C++'s copy and assignment constructors. So far what I have is in A.hpp:

class A {
private:
     char* str;
public:
     A(char* str);

     // strcpy str from other to this.
     A(const A& other);

     // free str in this, and strcpy str from other to this.
     A& operator=(const Type& other);
}

Assuming I have A* a = new A(some_char_str); , I'm able to write A b = *a;, and b is a deep copy of a. Now the problem is that I want the ability to write A* b = new A(a); So how can I specify a constructor that takes a pointer to A and create a new A on the heap?

3
  • 7
    Why not try it first? If there is an error, let us know. No need to suffer from "analysis paralysis". Commented Mar 27, 2015 at 17:45
  • 1
    @PaulMcKenzie Well... I just felt like I'm an idiot... I'm think about the copy/assignment constructor thing too hard... Commented Mar 27, 2015 at 17:48
  • 3
    @fleetC0m don't be hard on yourself. At least you gave it some thought, which is more than a lot of people do. Commented Mar 27, 2015 at 17:53

1 Answer 1

1

Oh well the brain fart... I just realized I can provide a constructor A::A(const A* other) myself without using copy/assignment constructor, or just write A* b = new A(*a); as suggested in comment.

Sign up to request clarification or add additional context in comments.

3 Comments

I think your original code had all of the necessary parts to perform what you requested. That's why I ask that you try it first.
BTW, If a is a pointer to an A, you had all the pieces already done in your original code: A* newA = new A(*a); This will call your copy constructor (which you coded) -- no need for another constructor that takes a pointer to A
@PaulMcKenzie When I try A* b = new A(*a);, I got error: no viable conversion from 'A *' to 'A'. That is without the A(const A* other); constructor of course

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.