I am doing a project on OOPs in C++ and getting some errors (Segmentation Fault).
sObjects
is a static vector containing pointers to every object created in the Base
class.
I have also checked the addresses by uncommenting the lines :
// cout<<(*it)<<endl;
// cout<<this<<endl;
.They are same.
So why I am getting garbage values/segmentation fault ? Do I have to do some sort of casting?
Here is my code:
//main.cpp
#include <iostream>
#include "Base.h"
using namespace std;
int main()
{
Base::UnitTest();
vector<Base *>::iterator it;
for (it = Base::sObjects.begin(); it < Base::sObjects.end(); ++it)
{
// cout<<(*it)<<endl;
cout<<(*(*it))<<endl;
}
return 0;
}
//Base.h
#ifndef BASE_H
#define BASE_H
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int val;
};
class Base
{
private:
Node node_;
public:
Base(int a=0);
~Base();
static vector<Base*> sObjects;
friend ostream &operator<<(ostream &os, const Base &myObj);
static void UnitTest();
};
#endif
//Base.cpp
#include "Base.h"
vector<Base*> Base::sObjects;
Base::Base(int a)
{
this->node_.val=a;
sObjects.push_back(this);
// cout<<this<<endl;
}
Base::~Base()
{
}
ostream &operator<<(ostream &os, const Base &myObj)
{
os<<myObj.node_.val;
return os;
}
void Base::UnitTest()
{
Base obj(23);
}