Reputation: 39
#include <iostream>
#include <vector>
using namespace std;
class Test
{
private:
int ID;
string name;
public:
Test(int ID, string name);
};
Test::Test(int ID, string name)
{
this->ID = ID;
this->name = name;
}
int main()
{
vector<Test *> test_vect;
Test *ptr = new Test(100, "John");
test_vect.push_back(ptr);
cout << ptr->ID << endl;
return 0;
}
This is a simple code I'm trying.
I want to access to the data that I stored in vector.
I thought it would be accessible by using ->
just like vector of struct but I can't. So I want to know how to load the data in class.
In addition, I thought sending data to heap section using new
would make it accessible at any time I want regardless of whether it is private or public, but it seems like it is not possible.
Can you explain how it works?
(I don't even fully understand how class
work, so detailed explanation would be very appreciated. Thx!)
Upvotes: 0
Views: 78
Reputation: 584
A private
variable cannot be accessed by code outside the class definition. (There are exceptions with friend
)
ptr->ID
does not work because main
is outside the class definition.
This can be fixed by using a getter method.
#include <iostream>
#include <vector>
using namespace std;
class Test
{
private:
int _ID;
string _name;
public:
int ID() {return _ID;}
string name() {return _name;}
Test(int param_ID, string param_name);
};
Test::Test(int param_ID, string param_name)
{
_ID = param_ID;
_name = param_name;
}
int main()
{
vector<Test *> test_vect;
Test *ptr = new Test(100, "John");
test_vect.push_back(ptr);
cout << ptr->ID() << endl;
return 0;
}
The above example shows the getter methods ID()
and name()
which return the data members _ID
and _name
respectively.
ID()
is allowed to access _ID
because ID()
is part of the class definition. name()
is allowed to access _name
because name()
is part of the class definition.
Note: I would still consider this code to be flawed because it creates a new object on the heap, but does not delete it. You should also look up the keywords new
and delete
to see how they operate together.
Upvotes: 1