[HELP] Pointer to a class

Hi.
I am having trouble using a pointer to a class. When i run this example i get an error message: "Segmentation fault (core dumped)".
Can someone help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class example
{
int a,b; 
public: 
void add(int c,int d) {this->a=c; this->b=d;};
void show() {cout<<this->a<<" "<<this->b;}
};

int main()
{
example *p;
p->add(10,15);
p->show();
return 0;
}




LE: I figured it out - i didn't allocate memory for my pointer...
Last edited on
Look at line 14: you declare a pointer to an instance of example, but you don't tell what instance it points to, so it doesn't point to anything. Still you try to use the functions of that absent instance. You can solve it like this:
1
2
3
4
5
6
7
8
int main()
{
    example instance;
    example *p = &instance;
    p->add(10,15);
    p->show();
    return 0;
}

Or like this:
1
2
3
4
5
6
7
8
int main()
{
    example *p = new example;
    p->add(10,15);
    p->show();
    delete p;
    return 0;
}

Don't forget the delete p part! Otherwise you will have memory leakage.
I did a similar thing:

1
2
3
4
5
6
7
8
9
int main()
{
example *p;
p=new example;
p->add(10,15);
p->show();
delete p;
return 0;
}
Last edited on
Topic archived. No new replies allowed.