# push_back

This topic is 4929 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello everyone, My class uses pointers and I'd like to add instances of it to a std::vector using push_back(). I've overloaded my class's equals (=) operator, but it now seems push_back doesn't use it. How can I ensure the vector's push_back method handles my class properly? Kind regards, Graham

##### Share on other sites
Assuming you're trying to hold a vector of pointers (if I've read you right)...

class YourClass;std::vector< YourClass *> vec;YourClass *x = new YourClass();vec.push_back( x );

##### Share on other sites
Normally all you need for functioning of push_back is the definition of a
copy constructor.

class MyClass
{
MyClass( MyClass& mc )
{...}

}

##### Share on other sites
He seems to be saying that his class uses pointers internally (as in, it's not a POD).

You need to know that operator= and the copy constructor are tied. More often than not, what is called by push_back is the copy constructor, and not the assignment operator.

##### Share on other sites
Thanks evolutional et al., it is the Copy Constructor I was looking for and not the equals operator.

( The class had member vars that were pointers. )

Thanks,
Graham

##### Share on other sites
Quote:
 Original post by Sparhawk42Normally all you need for functioning of push_back is the definition of a copy constructor.class MyClass{MyClass( MyClass& mc ){...}}

That is not a copy constructor, a copy constructor takes a constant reference. If you do that then there still is a copy constructor implicitly defined to do the default member-wise copy.

##### Share on other sites
Quote:
 Original post by snk_kidThat is not a copy constructor, a copy constructor takes a constant reference. If you do that then there still is a copy constructor implicitly defined to do the default member-wise copy.

Incorrect. A constructor for a class X that takes as an argument X & is a valid copy constructor. See section 12.1 paragraph 10 and section 12.8 paragraph 2 in the C++ standard.

##### Share on other sites
Quote:
 Original post by SiCraneIncorrect. A constructor for a class X that takes as an argument X & is a valid copy constructor. See section 12.1 paragraph 10 and section 12.8 paragraph 2 in the C++ standard.

Well its not a great idea to be doing in any case even though it is still a copy constructor, its good practice for copy constructors to take constant references. Constructors that take non constant references would be better for move semantics and move constructors if it ever gets standardized and/or supported by all C++ compilers.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 15
• 9
• 11
• 9
• 9
• ### Forum Statistics

• Total Topics
634135
• Total Posts
3015754
×