I have created few classes to introduce my problem. I am getting the segmentation fault error while I am trying to get data from objects whose pointers are in Storage class. This program hold the single pointer of First class type, which can hold FirstChild class object address. FirstChild class inherits from First class.
So, I have created two methods to get the data from the objects. First one (getNumbers())is the virtual method which is returning the value of the variables and the second one getNum() is calling the getNumbers() method.
The segmentation fault error means that I am trying to access to the memory that I do not have the access.
But is there the other way to get those values?
First.h
#ifndef FIRST_HPP
#define FIRST_HPP
class First {
protected:
int x;
public:
First(int x);
virtual ~First();
virtual int getNumbers();
}
#endif
First.cpp
#include "First.h"
First::First(int x) : x(x){}
int First::getNumbers(){
return this->x;
}
First::~First(){}
FirstChild.h
#ifndef FIRST_CHILD_HPP
#define FIRST_CHILD_HPP
class FirstChild : public First {
private:
int y;
public:
FirstChild(int x, int y);
virtual int getNumbers();
}
#endif
FirstChild.cpp
#include "FirstChild.h"
FirstChild::FirstChild(int x, int y) : First(x), y(y){}
int FirstChild::getNumbers() {
return this->x + this->y;
}
Storage.h
#ifndef STORAGE_HPP
#define STORAGE_HPP
#include "First.hpp"
class Storage {
private:
First * somePtr;
int z;
public:
Storage(First * ptr);
int getNum();
}
#endif
Storage.cpp
#include "Storage.h"
Storage::Storage(First * ptr) {
this->somePtr = ptr;
}
Storage::getNum(){
return this->somePtr->getNumbers(); //Segmentation fault (core dumped)
}
main.cpp
First * first;
FirstChild firstchild(10);
first= &firstchild;
Storage(first);
Storage.getNum(); //Segmentation fault
Aucun commentaire:
Enregistrer un commentaire