I am trying to add a pointer to an object in a pointer object vector. The 'message_list' vector lists pointers to an abstract class Message which is either adding a new Topic or Reply, two subclasses which inherit the superclass Message. My problem is when I try to add either a new Topic or a Reply to the vector, I get an error at compile time
error: no matching function for call to
'std::vector<Message*, std::allocator<Message*> >::push_back(Topic*&) const'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:602: note: candidates are:
void std::vector<_Tp, _Alloc>::push_back(const _Tp&)
[with_Tp
=Message*
,_Alloc
=std::allocator<Message*>
]<near match>
The error is on the line with the messag_list.push_back(msg)
:
Message* msg = new Topic( current_user->get_username(), subject, body, (message_list.size()+1) );
message_list.push_back(msg);
Why can't I add this pointer to my pointer vector? Thank you for the help!
EDIT: Here is the full function:
void Bboard::add_topic() const
{
string subject;
cout << "Enter Subject: ";
cin >> subject;
string body;
cout << "Enter Body: ";
cin >> body;
Message* msg = new Topic( current_user->get_username(), subject, body, (message_list.size()+1) );
message_list.push_back(msg);
cout << endl;
cout << "Message Recorded!" << endl;
cout << endl;
}
void Bboard::add_topic() const
Its a const member function which means this function promises not to modify the object, but the fact is that you want to modify the object, as message_list
is a member of the class and you're adding item to it. So const
is inappropriate here. Just remove it and make it as:
void Bboard::add_topic();
Problem solved!
A little more explanation :
In a const member function, every member of the class becomes const, unless its declared with the keyword mutable
, so in your const member function, message_list
is const object, so when you want to call push_back
on this object, the compiler generates error, because push_back
function can be called only on non-const object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.