0

I am trying to push a pointer into a vector, but my compiler gives me the error:

request for member 'Add_Object' in theContainer, which is of non-agregate type 'Container(X)'

Please tell me what I am doing wrong. Here is my code:

#include <vector.h>
#include <iostream>

class Object
{
private:
	short data;
public:
	Object(){data = 1;};
};

typedef Object::Object* pObject;

class Container
{
private:
	vector<pObject> v;
public:
	Container(){v.reserve(1);};
	void Add_Object(pObject o){v.push_back(o);}; // What am I doing wrong?
};

int main()
{
	Container theContainer();
	theContainer.Add_Object( new Object() ); // Compiler gives Error message Here
	return(0);
}

thanks for any advice you might offer.
wj

2
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by johnson9000
0

Lines in blue are the changes I made:

#include <vector>
#include <iostream>

using namespace std;

class Object
{
private:
	short data;
public:
	Object(){data = 1;};
};

typedef Object* pObject;

class Container
{
private:
	vector<pObject> v;
public:
	Container(){v.reserve(1);};
	void Add_Object(pObject o){v.push_back(o);};
};

int main()
{
	Container theContainer;
	theContainer.Add_Object( new Object() );
	return(0);
}

The first problem was that <vector.h> is not a standard header, it's <vector>. You also failed to take into account namespaces, so I added a global fix for it. Object is not a type name nested within the Object class, so Object::Object is nonsensical, and using empty parens to declare an object actually declares a function returning that object instead of calling the constructor.

0

So the correct declaration and use of a constructor with no parameters is:
/*Declare constructor*/ object();
/*Use constructor*/ newObject object;
Thanks for your help.
wj

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.