I'm having problem with the following code. I try to fill in a member of an object called station
inside a function, but I cannot retrieve it in main()
.
This is my header foo.h
class DirectoryProperties
{
public:
size_t numberOfFolders;
void initialize_stations( StationBase *station );
private:
void fill_station_names( StationBase *station );
};
class StationInfo
{
public:
std::string name;
};
And this is my foo.cpp
#include "foo.h"
void DirectoryProperties::fill_station_names( StationBase *station )
{
station[0].name = "dummy";
}
void DirectoryProperties::initialize_stations( StationBase *station )
{
size_t N = 1;
station = new StationBase[ N ];
this->fill_station_names( station );
// this works
std::cout << station[0].stationName << std::endl;
}
int main()
{
DirectoryProperties dirInfo;
StationBase *station = NULL;
dirInfo.initialize_stations( station );
// breaks here
std::cout << station[0].stationName << std::endl;
return 0;
}
So, I can correcly print station[0].name
inside DirectoryProperties::initialize_stations( StationBase *station )
, but no in main()
.
It also breaks if I try
int main()
{
DirectoryProperties dirInfo;
StationBase *station = NULL;
dirInfo.initialize_stations( station );
// breaks here
station[0].stationName = "dummy";
return 0;
}
So I assume that object pointer station
has no memory allocated in main
.
station
is a local variable in initialize_stations
, so no changes to it have an effect outside of the function.
An immediate fix is to have the function return a pointer to the newed array.
StationBase* DirectoryProperties::initialize_stations( )
{
....
StationBase* station = new StationBase[ N ];
....
return station;
}
A better solution is to return an std::vector<StationBase>
. Or just a single StationBase
, since you're only allocating one object anyway.
std::vector<stationBase> DirectoryProperties::initialize_stations()
{
size_t N = 1;
std::vector<stationBase> station(N);
fill_station_names( station );
return station;
}
and fix fill_station_names
accordingly.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments