I want to access and print the class pointer member variable from main()
without using any class member functions.
#include <iostream>
#include <string>
using namespace std;
class MyVector {
int* mem;
int size;
public:
MyVector();
MyVector(int n, int val);
~MyVector() { delete[]mem; }
// **I don't want to use this show() function**
void show(){
for (int i = 0; i < 10; i )
{
cout << mem[i] << endl;
}
}
};
MyVector::MyVector() {
mem = new int[100];
size = 100;
for (int i = 0; i < size; i )
{
mem[i] = 0;
}
}
MyVector::MyVector(int n, int val)
{
size = n;
for (int i = 0; i < size; i )
{
mem[i] = val;
}
}
How do I modify the code to access it like mem[index]
in the main()
function?
int main()
{
MyVector mv;
mv.show();
}
- The pointer
mem
variable of the class should remain the same. - I want to print the
mem
variable without using theshow()
function. - I want to know how to modify the code to access the
mem[index]
form.
For example:
int main()
{
MyVector mv;
for (int i = 0; i < 5; i )
{
cout << mem[index];
}
}
CodePudding user response:
C How can print dynamically allocated class variables without using class member functions
You can name data members outside of member functions if the members have public access (or if accessed from a friend). The data members in your example have private access, so they cannot be named outside of member functions (or friends).
That said, public data members cannot be looked up directly in a scope even if there is an instance of the class, so you cannot use mem
in main
to refer to the member. To access a non-static data member, you must use the member access operator .
to access the member through the instance.
You could achieve "I want to know how to modify the code to access the mem[index] form." by making a copy of the member:
class MyVector {
public:
int* mem;
// ...
MyVector mv;
int* mem = mv.mem;
std::cout << mem[index];
That said, given that you delete the member in destructor, it is an owning pointer, and it would be a terribly bad idea to make such pointer public. The encapsulation is essential to prevent code from outside of the class from breaking class invariants that are necessary to avoid memory leaks and undefined behaviour.
Also, your class is badly broken. If you make a copy (possibly without intending to do so), the behaviour of the program will be undefined due to deleting the same pointer more than once.
Also, the constructor MyVector::MyVector(int n, int val)
fails to initialise mem
and indirects through it, so the behaviour of the program will be undefined if you use that constructor.
CodePudding user response:
You would have to make the class members be public
:
class MyVector {
public:
int* mem;
int size;
...
};
And then access them via your mv
variable:
int main()
{
MyVector mv;
for (int i = 0; i < 5 /* or: mv.size */; i )
{
cout << mv.mem[i];
}
}