I am new to C++ and I'm trying to do the following:
1) I have created a class of objects called Objects which contains the name of the object and a number to identify them.
2) I have created a class Group which inherits from list, as follows:
#include "objects.h"
#include <list>
#include <iostream>
#include <string> using namespace std;
class Group : public std::list<Objects*> { private:
string groupname;
public:
Group(string groupname);
virtual ~Group() {} //destructor
virtual string getGroupName() const;
virtual void showlist(ostream & sl) const; };
3) Then, I have implemented the method showlist as follows:
void Groupe::showlist(ostream & sl) const{
printf("I'm here 1\n");
for(auto it = this->begin(); it != this->end(); it++){
printf("I'm here 2\n");
sl << this->getGroupName() << "test" << "test\n" << endl;
std::cout << "I'm alive";
} }
And the method getGroupName is as follows:
string Group::getGroupName() const{
return groupname;
}
4) In the main program I have created a pointer to a variable of type Group. The code compiles without any error, but when I executed it I realized that the program enters the method showlist and gets out without executing the for-loop. I have tested this by putting messages with printf. Just the messages "Before method", "I'm here 1", and "After method" are showed in the terminal. It doesn't show "I'm here 2". I call from main as follows:
Group *lgroup = new Group[5] {Group("g1"), Group("g2"),Group("g3"),Group("g4"),Group("g5")};
printf("Before method\n");
lgroup->showlist(sl);
printf("After method\n");
cout << sl.str() << endl;
Could you please help me to understand why the loop is not being executed?
Update
The program didn't enter to the loop because the list was empty, as explained in the answers of the members.
As for this case inheriting from List
is a constraint, I have filled the list in the main function as follows:
Groupe *lgroup1 = new Groupe("g1");
Object *objets[3];
objets[1] = new File("/home/Documents", "b2.jpg",0,0);
objets[2] = new File("/home/Documents", "b3.jpg",0,0);
objets[3] = new File("/home/Documents", "b4.jpg",0,0);
lgroup1->push_back(objets[1]);
lgroup1->push_back(objets[2]);
lgroup1->push_back(objets[3]);
Where File
is a class which inherits from the class Objects
. This way the program compiles and executes. In the command line it is shown the attribute of the class Groupe
, being g1
. I want to use the method display
which is already implemented in the class Objects
but when I try to do it the compiler shows this error:
error: 'const class Group' has no member named 'display'
sl << this->display(cout) << '\n' << endl;
So, my question is how can I make the class Group
to inherit the methods from both List
(which is already done) and Objects
?