class base{
public:
base(){x=0; y=0;}
base(int the_x, int the_y){x=the_x; y=the_y;}
protected:
int *array;
private:
int x;
int y;
};
class derieved : public base{
public:
derieved(){base(1,1); array[0]=1; array[1]=1;}
};
int main()
{
base *example;
example = new derieved;
}
the program compiles quitely but when I try to run, it gives me segmentation error. Neither could I understand the reason nor I could get around it.
#include <iostream>
usingnamespace std;
class base{
public:
base()
{
x = 0;
y = 0;
}
base(int the_x, int the_y)
{
x = the_x;
y = the_y;
}
protected:
int *array;
private:
int x;
int y;
};
class derieved : public base{
public:
derieved() : base(1,1){
array = newint[2];
array[0] = 1;
array[1] = 1;
}
};
int main()
{
base *example;
example = new derieved;
}
But there are still some issues, something like you should overload the copy constructor and assignment operator of class base, because there is a pointer in the class. And also delete the pointer in the destructor.
Thanks for reply, but I think while trying out myself I've opened up pandora's box for myself. I tried to initialized the array in base class itself. But still I run into segmentation error. Can't see why hooked's recipie works while following fails.(I have clipped out unnecessary data memebers).
@Anil79
Seems you did not understand the basic concept of a pointer in a class. Until unless you allocate memory where to store the given values, you can not assign a single value to it.
Per your code, you are stating that the array[0] and array[1] to hold value 1, but where???? what location???
A pointer is a variable points to a given/allocated memory address where the given values are stored in. Before you store a value, you should allocate (ie, reserve) memory for it.
That is what other posts are trying to explain you, using "new" operator. The "new" operator allocates given amount of memory and keeps the memory ready for your use. Check the example given by "hooked" again.