Sign in to follow this  
Belgium

error with vector of class with const members

Recommended Posts

When attempting to compile I receive the following error; "non-static const member `const std::string Cat::m_name', can't use default assignment operator" Why and what can I do, other than making 'm_name' not a constant, to fix this? I probably don't need to make m_name constant since I don't plan on offering a method which would allow changing it but I was curious about the error nonetheless. Thanks.

#include <iostream>
#include <string>
#include <vector>

class Cat
{
    public:
        Cat(std::string name);

        std::string getName() const {return m_name;}

    private:
        const std::string m_name;

};

Cat::Cat(std::string name)
  : m_name( name )
{}

int main()
{
    Cat spot("spot");
    std::cout << spot.getName() << "\n";

    std::vector<Cat> vCat;
    vCat.push_back( Cat("fido") );  // <-- The error message is triggering on this.  


    std::cin.get();
}



Compiler: Default compiler Compiler: Default compiler Executing g++.exe... g++.exe "C:\Main\Tools\Dev-Cpp\MyStuff\Tests\constMember.cpp" -o "C:\Main\Tools\Dev-Cpp\MyStuff\Tests\constMember.exe" -I"C:\Main\Tools\Dev-Cpp\lib\gcc\mingw32\3.4.2\include" -I"C:\Main\Tools\Dev-Cpp\include\c++\3.4.2\backward" -I"C:\Main\Tools\Dev-Cpp\include\c++\3.4.2\mingw32" -I"C:\Main\Tools\Dev-Cpp\include\c++\3.4.2" -I"C:\Main\Tools\Dev-Cpp\include" -I"C:\Main\Tools\Dev-Cpp\boost_1_34_0" -L"C:\Main\Tools\Dev-Cpp\lib" C:/Main/Tools/Dev-Cpp/include/c++/3.4.2/bits/vector.tcc: In member function `Cat& Cat::operator=(const Cat&)': C:/Main/Tools/Dev-Cpp/include/c++/3.4.2/bits/vector.tcc:238: instantiated from `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Cat, _Alloc = std::allocator<Cat>]' C:/Main/Tools/Dev-Cpp/include/c++/3.4.2/bits/stl_vector.h:564: instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Cat, _Alloc = std::allocator<Cat>]' C:\Main\Tools\Dev-Cpp\MyStuff\Tests\constMember.cpp:27: instantiated from here

Share this post


Link to post
Share on other sites
Quote:
Original post by Belgium
I probably don't need to make m_name constant since I don't plan on offering a
method which would allow changing it but I was curious about the error nonetheless.


std::vector requires the object to be assignable, which by default has to change the m_name value. If you do not wish to support assignment, don't use std::vector or manipulate the object by pointer.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this