Alon_T
Alon_T

Reputation: 1440

Invoking a copy constructor in C++

I have two pointers to class A declared globally

A* a;
A* b;

int main(){
     a = new A(...);           
}

How should I invoke a copy constructor to make b as copy BY VALUE of a. class A does not have any pointers as fields.

I do have a constructor declared, but I can remove it in order to not override the default one.

Thanks

Upvotes: 1

Views: 340

Answers (3)

Griwes
Griwes

Reputation: 9031

There are two things wrong with your code, that need to be fixed before answering the question.

  1. The fact that those global pointers are global - having something global, at global namespace, is sign of bad design (if your teacher is advocating it - because it seems kinda like homework - then slap him in the face for doing so).
  2. The fact that those global pointers are raw pointers - you either want to keep the ownership in their place and not pass the ownership around - then you'll use either unique_ptr or just plain object (unless the object is supposed to live longer than main(), but that's a weird case).

So, after correcting the code, it looks like this:

int main()
{
    A a;
    A b(a);      
}

If you need to access those objects from other parts of the code, without explicitly passing them around, put them in sensibly named namespace:

// in header
namespace a_and_b // this is *wrong* name for it, of course
{
    extern A a;
    extern A b;
}

// in one of TUs - also possible to wrap this in namespace ... { ... }
A a_and_b::a;
A a_and_b::b(a_and_b::a);

Of course, if you are just asking for syntax, the answer would be:

A * b = new A(*a);

so just dereference the pointer to get A out of A *. But please, don't ever do this - even in freestanding environment you can easily implement own smart pointer to wrap this in sane way.

Upvotes: 4

dutt
dutt

Reputation: 8209

If you don't declare one you always get an implicit constructor, copy constructor and destructor that you can call like StoryTeller said;

b = new A(*a);

If you want to do anything in the copy constructor you need to write one, here's a bit about how you do that: http://www.cplusplus.com/articles/y8hv0pDG/

Upvotes: 1

Simply call the copy constructor with new:

b = new A(*a);

I gotta ask though... why not keep two static objects instead?

Upvotes: 3

Related Questions