Accessing class variables in C++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Accessing Class Veriables in C++
Hi I have following class hierarchy in C++
Class1 {
vector<Class2> vecClass2;
}
Class2 {
private:
const Class1 * ptrClass1;
vector<Class3> vecClass3;
public:
Class2(const Class1 * ptrClass1);
int intC2publicVar;
string strC2publicVar;
}
Class3 {
private:
const Class2 * ptrClass2;
vector<Class4> vecClass4;
public:
Class3(const Class2 * ptrClass2);
}
Class4 {
private:
const Class3 * ptrClass3;
vector<Class5> vecClass5;
public:
Class4(const Class3 * ptrClass3);
void class4Method() const;
}
In class4Method() I am doing something like this:
void Class4::class4Method() const {
const Class2 * pC2 = ptrClass3->ptrClass2;
int valClass2 = pC2->intC2publicVar;
//Above value is giving wrong value, I have no idea from where it is fetching the wrong value
string strVatClass2 = pC2->strC2publicVar;
//Above line of code cause run time termination of code and programs stops as soon as this line executes.
const Class2 c2 = * pC2;
//Above line of code cause run time termination of code and programs stops as soon as this line executes.
}
I have no idea why this is happening in class4Method() of Class4. Please help me how to solve this. My whole project is struck due to this problem and I could not move further without solving it.

Do I assume correctly that the const ClassN-1* ptrClassN-1 members are pointers to "owners" of the current instance and that the instance they point to lives in a vector in the ClassN-2?
In that case you simply forgot that vectors have this habit of moving their content around the memory as they reallocate to accommodate newly inserted values. Don't store pointers to objects in vectors but either store the objects in list (and take pointer to the instance in the list, because it's still copied) or store vector of pointers (and make sure you delete the elements in destructor).

Related

Is there a problem with this class' constructor/destructor?

Im using this class in a larger function which isn't terminating properly.
I've had to resort to commenting out the algorithm one chunk at a time to narrow down where the problem is beginning.
The whole thing works as written but ultimately terminates in error and terminates the main() that is calling it.
Anyways, when I instantiate this class, the problem begins. Im assuming it must be a problem with the destructor, causing the error when the object falls out of scope.
Here is the class definition as well as the constructor/destructor:
class Entry
{
private:
int act_count; //number of activities for generating array MUST BE DETERMINED BEFORE INSTANTIATION
int ex_count; //number of expenditures for generating array
public:
Entry(int, int); // constructor
~Entry(); // destructor
string date; // functions like a title
Activity * act_arr; // pointer to an array of activities
Expenditure * ex_arr; // pointer to an array of expenditures
// list of member functions
};
struct Activity
{
public:
string a_name;
float time;
};
struct Expenditure
{
public:
string e_name;
float price;
};
Constructor:
Entry::Entry(int a_count, int e_count)
{
// initialization of basic members
date = day_o_year();
act_count = a_count;
ex_count = e_count;
// allocation of array space
act_arr = new Activity[act_count];
ex_arr = new Expenditure[ex_count];
}
Destructor:
Entry::~Entry()
{
// prevents memory leaks when object falls out of scope and is destroyed
delete act_arr;
delete ex_arr;
}
Are there any egregious errors here? I hope this isn't too much code to pique some interest.
Thanks in advance.
For starters, I think you need this (delete[] array):
Entry::~Entry() {
// prevents memory leaks when object falls out of scope and is destroyed
delete[] act_arr;
delete[] ex_arr;
}
But besides that, exactly what do you mean by "isn't terminating properly"?
Q: Do you have a stack trace/core dump?
Q: Have you stepped through code with the debugger?
Q: Do you have a specific error message you can copy/paste into your post?

Raw pointer to Singleton and Memory leak: Xcode doesn't show me any memory leaking

I designed my application to run such that I call a raw pointer on a class deriving from a Singleton:
class SimulatedIndexFixingStore : public Singleton<SimulatedIndexFixingStore>
{
private:
friend Singleton<SimulatedIndexFixingStore>;
typedef std::unordered_map<std::string, std::unordered_map<int, std::map<Date, double>>> Dictionary;
mutable Dictionary simulatedFixings_;
SimulatedIndexFixingStore& operator=(const SimulatedIndexFixingStore& ) = delete;
SimulatedIndexFixingStore(const SimulatedIndexFixingStore& ) = delete;
SimulatedIndexFixingStore();
~SimulatedIndexFixingStore()
{
std::cout << "\nCalling destructor of store...\n";
}
public:
// creates raw pointers to this store and passes them around...
static SimulatedIndexFixingStore* createPointerToStore()
{
auto tmp = new SimulatedIndexFixingStore() <----- memory allocation on the heap!;
return tmp;
}
};
I then use the raw pointer generated by the static member function SimulatedIndexFixingStore* createPointerToStore() and pass them around my application.
Question:
I don't call delete on the pointer prior to leaving the Main() function as this would call the destructor on the static Singleton instance, so this means I have a memory leak in my app. Correct?
I know for a fact that the destructor ~ SimulatedIndexFixingStore() is not getting called because the message is not printed out.
The instrument profiler of my application doesn't seem to agree there is a memory leak. Can someone please help me understand?
Thanks,
Amine

How to avoid memory leak with abstract class pointers

Let's assume I got an abstract class ("Book" in the example below) and some derived classes ("ElectroniBook","CodingBook" in the example below). I also want to keep a vector of books in a third class ("Library") and some maps to find them. Let's also assume that I need to create the "Library" from somewhere else using the "addBook" method and then assign it in the main.
Since Book is abstract I eventually need to delete the "Book" pointers I created and I want to do it in some destructor. Neverthless, whenever I try to use delete i got this error message
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
and if I try to replace raw pointers with shared_pointers or unique_pointers I immediately get errors at compile time telling me I'm trying to use pointers that have already been deleted. Note that I'm using C++ 11.
Here's some code just for example :
class Book{
public:
Book(string name, int Npages);
virtual ~Book();
virtual void displayBook() = 0;
private:
string _name;
int _Npages;
}
class ElectronicBook : public Book{
public:
ElectronicBook(string name, int Npages);
~ElectronicBook();
void displayBook() { //do something
};
}
class CodingBook : public Book{
public:
CodingBook(string name, int Npages);
~CodingBook();
void displayBook() { // do something else
};
}
class Library{
public :
Library();
~Library(){
// this doesn't work for me
// for(auto & a : _books)
// delete a;
// _books.clear();
//
//for(int i=0;i<_bookmap.size();++i)
// delete bookmap.at(i);
};
void addCodingBook(string name, int Npages){
CodingBook* cb = new CodingBook(name, Npages);
_books.push_back(cb);
_bookmap[name] = cb;
//should I delete anything here?
};
void addEletronicBook(string name, int Npages){
ElectronicBook* eb = new ElectronicBook(name, Npages);
_books.push_back(eb);
_bookmap[name] = eb;
//should I delete anything here?
};
private :
vector<Book*> _books;
map<string, Book*> bookmap;
}
// separeted function
Library createLibrary(){
Library L;
while(...){
//read books from somewhere(file, input or whatever) and
// addElectronicBook(...)
// addCodingBook(...)
}
return L;
}
int main(){
Library myLibrary = createLibrary();
// do something with Library
}
Since I did several times "new" to add Books, I need to delete them. I tried to do it in the Library destructor like I showed but I got the error mentioned before.
If I understand correctly your issue, you are freeing twice the same memory:
// for(auto & a : _books)
// delete a;
// _books.clear();
//
//for(int i=0;i<_bookmap.size();++i)
// delete bookmap.at(i);
Both _books and bookmap contain pointers that are pointing to the same ares of memory and you are freeing them twice.
When working with raw pointers you have to decide who is the owner of the memory, say, for example _books and who has simply access to the memory but is not responsible for the cleanup.
So, you should:
delete only once, so use only one of the two for loops, say for the sake of argument _books
make sure that the other non-owning structures, say bookmap in our example, never, ever access the memory (i.e. de-reference the pointer) after the deletion
Suggestion: put in the vector unique_ptr so the vector is the owner and put raw pointers in the map to signal that the map is not owning. unique_ptr will take care of cleaning up the memory for you. If you want to be sure, add some print statements or put break points in the destructors if you have a debugger.

Vector of Object Pointers, general help and confusion

Have a homework assignment in which I'm supposed to create a vector of pointers to objects
Later on down the load, I'll be using inheritance/polymorphism to extend the class to include fees for two-day delivery, next day air, etc. However, that is not my concern right now. The final goal of the current program is to just print out every object's content in the vector (name & address) and find it's shipping cost (weight*cost).
My Trouble is not with the logic, I'm just confused on few points related to objects/pointers/vectors in general. But first my code. I basically cut out everything that does not mater right now, int main, will have user input, but right now I hard-coded two examples.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Package {
public:
Package(); //default constructor
Package(string d_name, string d_add, string d_zip, string d_city, string d_state, double c, double w);
double calculateCost(double, double);
~Package();
private:
string dest_name;
string dest_address;
string dest_zip;
string dest_city;
string dest_state;
double weight;
double cost;
};
Package::Package()
{
cout<<"Constucting Package Object with default values: "<<endl;
string dest_name="";
string dest_address="";
string dest_zip="";
string dest_city="";
string dest_state="";
double weight=0;
double cost=0;
}
Package::Package(string d_name, string d_add, string d_zip, string d_city, string d_state, string r_name, string r_add, string r_zip, string r_city, string r_state, double w, double c){
cout<<"Constucting Package Object with user defined values: "<<endl;
string dest_name=d_name;
string dest_address=d_add;
string dest_zip=d_zip;
string dest_city=d_city;
string dest_state=d_state;
double weight=w;
double cost=c;
}
Package::~Package()
{
cout<<"Deconstructing Package Object!"<<endl;
delete Package;
}
double Package::calculateCost(double x, double y){
return x+y;
}
int main(){
double cost=0;
vector<Package*> shipment;
cout<<"Enter Shipping Cost: "<<endl;
cin>>cost;
shipment.push_back(new Package("tom r","123 thunder road", "90210", "Red Bank", "NJ", cost, 10.5));
shipment.push_back(new Package ("Harry Potter","10 Madison Avenue", "55555", "New York", "NY", cost, 32.3));
return 0;
}
So my questions are:
I'm told I have to use a vector
of Object Pointers, not Objects.
Why? My assignment calls for it
specifically, but I'm also told it
won't work otherwise.
Where should I be creating this
vector?
Should it be part of my Package
Class? How do I go about adding
objects into it then?
Do I need a copy constructor? Why?
What's the proper way to deconstruct
my vector of object pointers?
Any help would be appreciated. I've searched for a lot of related articles on here and I realize that my program will have memory leaks. Using one of the specialized ptrs from boost:: will not be available for me to use. Right now, I'm more concerned with getting the foundation of my program built. That way I can actually get down to the functionality I need to create.
Thanks.
A vector of pointers can be reused for storing objects of sub-classes:
class Person
{
public:
virtual const std::string& to_string () = 0;
virtual ~Person () { }
};
class Student : public Person
{
const std::string& to_string ()
{
// return name + grade
}
};
class Employee : public Person
{
const std::string& to_string ()
{
// return name + salary
}
};
std::vector<Person*> persons;
person.push_back (new Student (name, grade));
person.push_back (new Employee (name, salary));
person[0]->to_string (); // name + grade
person[1]->to_string (); // name + salary
Ideally the vector should be wrapped up in a class. This makes memory management easier. It also facilitates changing the support data structure (here an std::vector) without breaking existing client code:
class PersonList
{
public:
Person* AddStudent (const std::string& name, int grade)
{
Person* p = new Student (name, grade);
persons.push_back (p);
return p;
}
Person* AddEmployee (const std::string& name, double salary)
{
Person* p = new Employee (name, salary);
persons.push_back (p);
return p;
}
~PersonList ()
{
size_t sz = persons.size ();
for (size_t i = 0; i < sz; ++i)
delete persons[i];
}
private
std::vector<Person*> persons;
};
So we can re-write our code as:
{
PersonList persons;
Person* student = persons.AddStudent (name, grade);
Person* employee = persons.AddEmployee (name, salary);
student.to_string ();
employee.to_string ();
} // The memory allocated for the Person objects will be deleted when
// `persons` go out of scope here.
Getting familiar with the Rule of Three will help you decide when to add a copy constructor to a class. Also read about const correctness.
Question 1:
You mentioned inheritance. Since inherited objects often need more bytes of storage, they don't fit into the place of a base object. If you try to put them in, you get a base object instead. This is called object slicing.
Question 2:
Design first, before you write code. There are a bunch of possible solutions.
For a start you can keep it in main(), but later you will be forced to make a class like PackageContainer for holding your objects.
Question 3 + 4:
You need a copy constructor, an assignment operator= and a destructor, when a class object owns dynamically allocated objects (the Rule of the Big Three). So a PackageContainer will probably need them.
You create objects dynamically using new Object(..). You are responsible for destroying them and for giving their memory back to the system immediately before your vector of pointers is destroyed:
for (size_t i = 0; i < shipment.size(); ++i)
{
delete shipment[i];
}
Since working with naked pointers to dynamically allocated objects is not safe, consider using
std::vector<tr1::shared_ptr<Package> > shipment;
instead or
std::vector<std::shared_ptr<Package> > shipment;
if your compiler understands C++0x. The shared_ptr handles freeing memory for you: It implements the Rule of the Big Three for one object pointer. It should be used in production quality code.
But try to get it right with naked pointers also. I think that's what your homework assignment is about.
I'm told I have to use a vector of Object Pointers, not Objects. Why? My assignment calls for it specifically, but I'm also told it won't work otherwise.
Usually, one would avoid using vector of objects to avoid the problem of Object Slicing. To make polymorphism work You have to use some kind of pointers. I am not sure of how the classes in your assignment are aligned but probably you might have Inheritance there somewhere and hence if vector is storing objects of Base class and you insert objects of Derived class in it then it would cause the derived class members to slice off.
The Best solution will be to use a smart pointer instead of a Raw pointer. The STL has an auto_ptr, but that cannot be used in a standard container.Boost smart pointers would be a best solution but as you already said you can't use Boost So in your case you can use your compiler's implementation of smart pointers, which comes in TR1 namespace,remember though that there is some disagreement on the namespace for TR1 functions (Visual C++ puts them in std::, while GCC puts them in std::tr1::).
Where should I be creating this vector? Should it be part of my Package Class? How do I go about adding objects into it then?
Your example code already has an example of adding a pointer to Package class in a vector. In a nutshell you will dynamically allocate pointers to Package and then add them to the vector.
Do I need a copy constructor? Why?
The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:
class MyClass {
public:
MyClass( const char* str );
~MyClass();
private:
char* str;
};
MyClass::MyClass( const char* str2 )
{
str = new char[srtlen( str2 ) + 1 ];
strcpy( str, str2 );
}
Class::~Class()
{
delete[] str;
}
In this case member-wise copying of str member will not duplicate the buffer (only the pointer will be copied(shallow copy)), so the first to be destroyed copy sharing the buffer will call delete[] successfully and the second will run into Undefined Behavior. You need deep copying copy constructor (and assignment operator as well) in such a scenario.
When to use a custom copy constructor is best defined by the Rule Of Three:
Whenever you are writing either one of Destructor, Copy Constructor or Copy Assignment Operator, you probably need to write the other two.
What's the proper way to deconstruct my vector of object pointers?
You will have to explicitly call delete on each contained pointer to delete the content it is pointing to.
vector::erase
Removes from the vector container and calls its destructor but If the contained object is a pointer it doesnt take ownership of destroying it.
Check out this answer here to know how to corrctly delete a vector of pointer to objects.

deleting memory for static variable in C++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
deleting memory allocated in static function in C++
Hi All,
I have C++ class as follows
interface myInterface;
class anotherClass : public myInterface {};
class myClass {
private:
myClass() {}
~myClass() {}
typedef std::map<string, myInterface* > stringToClass;
static stringToClass s_stringToClass;
public:
static myInterface& getStringToclass(string name);
};
in above class for getStringToClass defintion is as follows
myInterface& myClass::getStringToClass(string name) {
stringToClass::iterator iter;
iter = s_stringToClass.find(name);
if(iter == s_stringToClass.end()) {
typedef stringToClass::value_type stringToClassPair;
anotherClass* pothClass = new anotherClass();
s_stringToClass.insert(stringToClassPair(name, pothClass));
return pothClass;
}
else {
return iter->second;
}
}
now my question is we are allocating memory in static function and returning a pointer of class type, but here i want to retrun a reference as we don't want to give control of pointer to user. And also i don't want to delete immedetily unless user asked to or want to delete at end of program How can we delete memory? As there is only instance of class will be there, as there are only static functions.
Thanks for the help.
Note:
You should reformat on the old thread, instead of creating new question. Anyway, I paste my answer here.
I think in your case, the destructor won't help, because there is no any object of MyClass.
I propose three ways
1. Don't store pointer, store the object itself.
2. Put the delete function into atexit; In your case
class MyClass
{
.....//Your already existing code
static void Destroy()
{
//iterate s_StringToClass and delete them
}
static void getStringToClass( string name )
{
struct DestroySetter
{
DestroySetter()
{
atexit( MyClass::Destroy );
}
};
static DestroySetter setter; //Setup the destoyer
//Your existing code here
}
Use smart pointer to manage the resource, shared_ptr is recommended.
Though I put a lot in second way, I suggest the 3rd way.