hi I'm just learning the c++ . I have following doubt . I write a simple code but when i compile it shows errors . my code is following:
code :
#include<iostream>
using namespace std ;
class abc
{
public:
int x,y,z ;
public: abc()
{ x=10,y=20;z=30 ;}
};
int main()
{
abc* a;
a->x = 50;
cout<<a->x;
}
it compiled successfully but when i run it it shows segmentation fault .
can anybody explain me why it is showing segmentation fault ?
Than i just change the access modifier in code like following :
code :
private :
int x,y,z ;
When i compile it it shows the following error :
xyz.cpp: In function ‘int main()’:
xyz.cpp:6: error: ‘int abc::x’ is private
xyz.cpp:14: error: within this context
xyz.cpp:6: error: ‘int abc::x’ is private
xyz.cpp:15: error: within this context
Now my questions are following :
what is the difference between object pointer and class pointer ?
How to declare and use object pointer and class pointer ?
Is there any possible way to access the private member of class without using member function ?
Can we use object pointer or class pointer to access the private data member of class ?
#include<iostream>
usingnamespace std ;
class abc
{
public:
int x,y,z;
abc()
{ x=10;y=20;z=30 ;}
};
int main()
{
abc *a=new abc;
a->x = 50;
cout<<(*a).x;
system ("pause");
}
if you wish access to private members of class you have to use function for acess to them
if you wish declare pointer you have to reserved memory first
1. abc *a; a->x = 50; - This code will not give a compiler warning/error but is incorrect. Pointer a is assigned to an undefined location and assigning it data without changing the location of that pointer to one that is known will result in undefined behavior. This is most likely causing the segmentation fault.
2. abc() { x=10;y=20;z=30 ;} - This code functions correctly but has an easy and often missed optimization to it. You can use the constructor's initializer list like so: abc() : x(10), y(20), z(30) {}