I've got this:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <sstream>

using namespace std;

class alfa{
		int x;
			cout<<"Dimiourgithike ena alfa"<<endl;
			cout<<"Katastrafike ena alfa"<<endl;
	void get_x(){
		cout<<"To x exei timi: "<<x<<endl;

int main(){
	alfa* alfadi;
	int no;
	cout<<"Dose enan arithmo"<<endl;
	vector<alfa> alfadia;
	for(int i=0;i<no;i++){
		alfadi=new alfa;

But i get error on push_back() while compiling.Any ideas?

>> But i get error on push_back() while compiling.

The alfadia vector stores objects of type alfa , not pointers to such objects. Then again new alfa returns a pointer to the allocated alfa object.

So, if you want to store objects ...

// vector for storing objects ...
vector<alfa> alfadia;
for(int i=0;i<no;i++)
  // 'obj' below, is constructed via default ctor
  alfa obj;

And if you want to store pointers to objects ...

// vector for storing pointers ...
vector<alfa * > alfadia;
for(int i=0;i<no;i++)
  // allocate one alfa object constructed via default ctor
  alfa * obj_pointer = new alfa;

or u can change to..


Yes, that will push a copy-constructed object onto the vector, however, the object pointed by alfadi has to be deleted to avoid leaking memory.

This article has been dead for over six months. Start a new discussion instead.