Deleting all pointers to same object - c++

I have something like this:
void foo(){
Student *a0 = new Student();
Student *a1 = new Student();
Student *a2 = new Student();
Student *a3 = new Student();
}
I have another function
void foo2(){
Student* delStudent;
delStudent = ll.ReturnStudentToDelete(); //this function returns a pointer to delete student
delete delStudent ;
delStudent = NULL;
}
suppose, ll.ReturnStudentToDelete() returns address of a2, above code deletes this object. I want also to set pointer 'a2' to NULL. But I don't know how to retrieve a2 pointer so that to set it to NULL.
Currently I have 2 pointers (a2 and selStudent) which point to same object
Also, I was asked to use operator*() and operator->(). But I didn't get that at all, so I try to do my best. Could you please post simple template example of how that may be implemented. I understand that above raw pointers are bad to use

Based on your code, since you do this:
void foo(){
Student *a0 = new Student();
...
}
Actually, you never store the pointers. In fact this means that when you call foo you will instantly leak all of the memory you create, because you have not stored these pointers. Not only can the ll.ReturnStudentToDelete() function not get the a2 pointer, it won't be able to get any relevant pointer.
You should start with seeing if you can avoid using a pointer. For example, perhaps your code could work like this:
Student someStudent;
...
someStudent.doSomething();
Or if you really do need a group of students:
std::vector<Student> groupOfStudents;

Related

Make instance of class on existing variable

How i can make c++ instance on existing variable
This is my header:
#ifndef PERSON_H_
#define PERSON_H_
class Person{
private:
std::string name = "default";
public:
void setName(std::string name);
}
#endif
This is my person.cpp
#include "person.h";
void setName(std::string name){
this->name=name;
}
And my main cpp file
#include <iostream>
int main(){
Person p;
p.setName("Jack");
//so person now have name Jack.
//here is my problem
p=new Person;
//get error.So how i can on variable p make new instance of Person for return all to default values
return 0;
}
p = Person();. In most cases p = {}; will also work.
new gives you a pointer to a new instance of Person. A HolyBlackCat pointed out, you are not using a pointer here. So either use p = Person() or go with pointers from the very beginning with Person *p = new Person(). However, in this case, I really do not see any need for pointers.
Person* p = new Person(); If you do want to make a new instance use pointer of type Person which will point to the memory address allotted by the new operator. Do whatever operation you want to perform. Since you are using new, make sure to use a delete operator to prevent memory leaks.delete p; delete will basically delete the value at the address pointed by p and assign a nullptr to it so that it doesn't become a dangling pointer. Then again if you want to assign new instance you can use the new operator. Now will p point to a different memory location which is the address of the new object.
-Person *p = new Person();
//perform operations
delete p;
p = new Person();

C++ Is delete[] enough to clean up after an array?

In the code below I'm allocating an array dynamically by using the new keyword. Before I run out of scope I call delete[] on my array, and afterwards I set the punter to null.
My Question is, if this is enough, will delete[] make sure that the allocated memory for all 3 Car objects in my array is released. Or do I have to do something specific to release the memory used by every single object?
void main()
{
Car * myArray = new Car[]{ * new Car("BMW"),*new Car("AUDI"), * new Car("SKODA") };
delete[] myArray;
myArray = nullptr;
}
Also, the car class looks like this. Is it also enough to set the name to null here. Name is a char pointer. Or maybe it isn't needed to set the pointer to null since it isn't referencing anything on the heap.
Car::Car(char * newName)
{
name = newName;
}
Car::~Car()
{
name = nullptr;
}
EDIT:
First of all, thanks for all the great answers and comments. I learned a lot from reading them.
Now I understand, that I need to specify a size when declaring a dynamic allocated array.
Besides that I also understand, that I need to stop using new as much as I do. I guess its better to throw the objects on the stack, and let them go out of scope at some point. Besides that I guess my destructor on my car does nothing.
After reading the comments and the answers, I'v change my code to this:
int main()
{
Car * myArray = new Car[3]{ Car("BMW"), Car("AUDI"), Car("SKODA") };
delete[] myArray;
myArray = nullptr;
}
In your case, you have already leaked the memory from your calls to new Car("BMW") and have lost the pointer to be able to free the memory.
This line:
Car * myArray = new Car[]{ * new Car("BMW"),*new Car("AUDI"), * new Car("SKODA") };
Creates an array of 3 Car objects, then for each entry it creates a new Car object, uses it to initialize the object in the array, then forgets about the new object.
It can be more simply written like this:
Car * myArray = new Car[3]{ Car("BMW"), Car("AUDI"), Car("SKODA") };
or even
Car * myArray = new Car[3]{ "BMW", "AUDI", "SKODA" };
In which case your delete[] is enough to free up the memory used.
Note that
Car::~Car()
{
name = nullptr;
}
does not do anything to free memory. Once the Car destructor is called, no one should be accessing name for that object again (in fact it is undefined behavior), so there is little point in setting it to null.
Edit Note: As pointed out by R Sahu and Aslak Berby, Car * myArray = new Car[]{ ... }; is not a valid way to make an array, use Car * myArray = new Car[3]{ ... }; instead.
You cannot use:
Car * myArray = new Car[]{ * new Car("BMW"),*new Car("AUDI"), * new Car("SKODA") };
You need to specify a size.
Car * myArray = new Car[3]{ * new Car("BMW"),*new Car("AUDI"), * new Car("SKODA") };
Even after that, calling
delete [] myArrary;
is going to leak memory. That line is equivalent to:
Car * myArray = new Car[3];
Car* car1 = new Car("BMW");
Car* car2 = new Car("AUDI");
Car* car3 = new Car("SKODA");
myArray[0] = *car1;
myArray[1] = *car2;
myArray[2] = *car3;
The line
delete [] myArrary;
does not delete the objects allocated separately for car1, car2, and car3. You'll have to explicitly delete those too.
delete car3;
delete car2;
delete car1;
However, you cannot use
Car * myArray = new Car[3];
since Car does no have a default constructor. You can add a default constructor to Car. Failing that you can to use:
Car * myArray = new Car[3]{ Car("BMW"), Car("AUDI"), Car("SKODA") };
Then, it is sufficient to use:
delete [] myArrary;
to deallocate the memory.
Car * myArray = new Car[X];
This code already creates X Car objects. All you have to do is use them really..
However, I think your confussion lies here: this is another approach to do it
Car ** myArray = new Car*[3] { new Car("BMW"), new Car("AUDI"), new Car("SKODA") };
for (int i = 0; i < 3; i++)
delete myArray[i];
delete[] myArray;
This code allocates an array of 3 Car* pointers. Therefore, you have not created any Car object yet, which is why you initialize each Car* pointer with with a new Car() call, which actually creates the Car object.
yes it is sufficient only if you are creating a plain array of Car elements since an array name is a pointer to its first element
You are informing the compiler that its an array by specifying the []
In your case you seem to be creating car pointers so you have to clean up the memory location occupied by each car and then the memory allocated for the whole array.
What you incorrectly attempted to do is this but don't do it. Its convoluted
Car** cararrptr = new Car*[3];
cararrptr[0] = new Car("win");
cararrptr[1] = new Car("lin");
cararrptr[2] = new Car("ios");
//now to clean up
delete cararrptr[0];
delete cararrptr[1];
delete cararrptr[2];
delete[] cararrptr;
Take a look at this discussion
delete[] an array of objects
Basically you need a delete (or delete[]) for every new. But in a more complex program this can be very difficult (and error prone) to assure.
Instead of raw pointers you should learn to use smart pointers like shared_ptr or unique_ptr. These let you avoid explicit new and delete in most cases.
I agree with the comments that you are using the keyword new too much.
I suggest using std::vector instead.
Here is a working example where the class Garage has a vector of Car's on the heap/freestore and later deleting it with destructor ~Garage
Example for illustration only:
class Car {
Car();
string m_name;
public:
Car(const string &);
void print();
};
Car::Car(const string &s) : m_name{s} { }
void Car::print()
{
cout << m_name << endl;
}
class Garage {
string m_name;
vector<Car> *m_cars; // for allocating on heap
public:
Garage(const string &);
~Garage();
void add(const Car &);
void print();
};
// Creating a new vector on heap
Garage::Garage(const string &s) : m_name{s}, m_cars{new vector<Car>} { }
Garage::~Garage()
{
delete m_cars; // deleting the vector.
}
void Garage::add(const Car &c)
{
m_cars->push_back(c);
}
void Garage::print()
{
for (auto car : *m_cars)
car.print();
}
int main()
{
Garage garage{"Luxury garage"};
garage.add(Car("BMW"));
garage.add(Car("Audi"));
garage.add(Car("Skoda"));
garage.print();
}
Using new vector above is only for demonstration, it's not needed. Using a std::vector without new is faster and safer for this purpose and you won't need to delete it after use.
Also consider using Smart Pointers instead of using new.
You can add a object to the heap or the stack. If you add it to the heap you create it dynamicaly as you go. This is done using new and you get a pointer in return.
Car *aCar=new Car("BMW");
If you create it on the stack, you will just define it as you do with other variables.
Car anotherCar("BMW");
If you create it on the heap, you also need to deallocate it from the heap. This is done with delete.
delete aCar;
You never dealocate a object you created on the stack. That will automtically be dealocated when you go out of scope.
As for creating a array, you can create a array of statick or dynamicall objects.
Dynamical:
Car **cars=new Car*[3];
cars[0]=new Car("BMW");
cars[1]=new Car ....
All of those need to be deleted seperatly. No cascading here.
delete cars[0];
delete cars[1];
// And finaly the array.
delete[] cars;
You can create them staicaly:
Car cars[]={"BWM", "AUDI"};
This time all the objects including the array is pushed to the stack and will be deleted when you go out of scope.
In between you can create stuff that is a stackbased array that points to heap allocated objects, or a heapallocated static array as other suggest here.
As for C++ I would suggest using the std:: library and in this case std::vector;
Either:
std::vector<Car *> myArray;
myArray.push_back(new Car("BMW"));
.....
// Cleanup:
for(auto car : myArray)
delete car;
Or:
Car car;
std::vector<Car> myArray;
car.SetType("BMW");
myArray.push_back(std::move(car));
I am not sure how I ended up here on a two year old post. None of the answers really give a simple C++ solution so here is a 60 second solution using containers and no new/delete in sight.
#include <iostream>
#include <string>
#include <vector>
struct Car {
// Allows implicit conversion from char *
Car(const char *manufacturer) : manufacturer_(manufacturer) {}
std::string manufacturer_;
};
int main() {
std::vector<Car> cars{ "BMW", "AUDI", "SKODA" };
for (const auto& car : cars) {
std::cout << car.manufacturer_ << "\n";
}
}
live demo
No. delete []myArray Will merely result in something called a dangling pointer.
Which basically means that the program no longer owns the memory pointed to
myArray, but myArray still points to that memory.
To avoid dangling pointers assign your pointer to nullptr after deletion.
delete[]myArray;
myArray = nullptr;

How to implement a dynamic array of object pointers? "expression must be a modifiable lvalue"

I'm a c++ student and this is my second post here. I'm working on a class whose job is to maintain an array of object pointers. (That way a pointer can be passed in and added to the array, instead of the entire object.)
The array is supposed to be dynamic but I'm running into some errors when I try to dynamically allocate memory for it. The following code produces the error "expression must be a modifiable lvalue" at studArray, as marked.
#ifndef MYCLASS_H
#define MYCLASS_H
#include "Student.h"
class myClass{
private:
Student* studArray[5];
int howMany;
int max;
public:
myClass(){
Student firstOne;
studArray[0] = &firstOne;
howMany=0;
max=5;
}//myClass()
void insertEl( Student* nextEl ){
howMany++;
if(howMany >= max){
Student** tempPt = new Student* [max + 1];
for( int i = 0; i < currentNum; i++){
tempPt[i] = studArray[i];
}
delete [] studArray;
studArray = tempPt; // <-------------------------error
}
studArray[ howMany ] = nextEl;
}//insertEl
};
I tried changing the original Student * array to have no size specified, but that produced the error "incomplete type is not allowed" at studArray.
class myClass{
private:
Student* studArray[]; <------------- error
int howMany;
int max;
What am I doing wrong?
(Thank you for the help!)
For reference I'm using Win 7 64bit, Visual Studio Professional 2012.
Assumptions: Instructor want you to learn the fine art of memory management on your own. So no library containers and no smart pointers. When you have the time, look into how to use the standard containers and the smart pointers. They'll save you a huge amount of time and grief in the future.
First, declaring the Student array.
Student* studArray[5];
You have the crux of it right here
Student** tempPt = new Student* [max + 1];
So try
Student** studArray;
And then hack your constructor to allocate the storage
myClass()
{
max = 5;
studArray = new Student*[max]; /* For improved safety, read up on
exceptions, catch and handle the
out of memory exception */
howMany = 0;
} //myClass()
I recommend adding a destructor to handle the clean up and put back your array.
virtual ~myClass()
{
delete[] studArray;
}
Check with the assignment notes or the instructor to see who is responsible maintaining the Students. You may have to revisit the destructor to delete all of the Students before deleting studArray
Additional note:
myClass()
{
Student firstOne;
studArray[0] = &firstOne;
howMany=0;
max=5;
}//myClass()
Student firstOne; is a temporary variable. firstOne only exists between the closest enclosing {} braces. This is called Scope. Using any value outside of it's scope will have unpredictable results and most likely crash the program. Frankly, that's if you are lucky. The program may limp on for some indeterminate time and crash later.
The assignment studArray[0] = &firstOne; is dangerous because by the time anyone tries to use studArray[0], the data at which it points will not be valid. firstOnedoes not exist outside the constructor. If you want firstOne to go on living, you will have to define it as a pointer, create it with new, and delete it when it is no longer needed. In this case I don't think you ever need it.
Another suggestion is to double the size of studArray rather then simply adding one when it is full. This way you don't have to reallocate the storage and copy all of the existing students to the new storage as often.
A better method is to have a std::vector of Student:
std::vector<Student *> maleStuds;
std::vector<Student *> femaleStuds;
Or, if you must use arrays:
const unsigned int MAXIMUM_STUDENTS = 5;
Student * students[MAXIMUM_STUDENTS];
For dynamic:
Student * * students = new Student * [MAXIMUM_STUDENTS];

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.

Segfault when assigning one pointer to another

My brain has never really quite grasped linked lists and the finer points of pointers but I'm trying to help out a friend with some C++ assignments. (And before I go any further, yes, there is std::list but I'm looking for an academic answer, and maybe something that will make linked lists more understandable to he and myself).
What we need to do is generate a linked list of objects (a Employee object) based on user input, and then display that information back to the user. Whenever I try to assign the object into the Linked List Container, it segfaults.
I have the following Linked List object:
class LinkedListContainer {
private:
Employee *emp;
LinkedListContainer *next;
public:
Employee getEmployee() { return *emp; }
void setEmployee(Employee *newEmp) {
*emp = *newEmp // This is what is causing the segfault
}
LinkedListContainer getNext() { return *next; }
void setNext(LinkedListContainer *newContainer) {
*next = *newContainer;
}
}
I'm sure that I'm doing something horribly wrong.
Looking at your class, there doesn't appear to be a place where the pointer emp is set to point at an actual object.
This line:
*emp = *newEmp;
assigns the value of the object pointed to by newEmp to the object pointed to by emp. Unless both pointers point at valid objects, the code will have undefined behaviour.
You may be better having emp as an Employee object rather than as a pointer to an object requiring manually management of the pointed to object's lifetime.
This assumes that your LinkedListContainer class is a node which will own the Employee.
On the other hand when you do:
*next = *newContainer;
from the naming I would assume that you just want to point the next pointer at another LinkedListContainer for which you would probably want to do:
next = newContainer;
as this assigns the value of the pointer to the variable next.
You need to be clear when you design your class and use pointers, on which objects own which other objects and ensure that you manage their lifetimes appropriately.
*emp = *newEmp;
Should be:
emp = newEmp;
So that you're assigning the pointer and not the object pointed to by the pointer.
Your emp pointer is uninitialized, so when you attempt to dereference it (*emp) in setEmployee() you attempt to access memory that doesn't belong to you (hence the segfault).
You might be better off holding the Employee by value (assuming it's not polymorphic) and passing the setEmployee an Employee object by const reference:
class LinkedListContainer {
Employee emp;
// ...
void setEmployee(const Employee& newEmp) {
emp = newEmp;
}
// ...
};
Of course, you'll need to adjust your other member functions as well to reflect using a value vs. a pointer.
Good luck!
*emp = *newEmp
You don't want to do this - in fact, you don't want to dereference any pointers at all here.
emp = newEmp
By default, emp is a pointer that's pointing nowhere. By writing
*emp = *newEmp;
you try to assign the content of newEmp to whatever memory location is pointed to by emp. As said, emp is pointing nowhere, so you are dereferencing a NULL pointer here, which is causing the segmentation fault.
If your container is to contain a complete Employee, you'd better declare emp to be of type Employee (not pointer to Employee as now). Then
emp = *newEmp;
will work, although I'm not quite sure whether this will be all you'd need to fix about your LinkedListContainer.
One of the issues that you are having is because of the leading * when you access the pointer. What * tells the compiler when accessing a pointer is that instead of reading the address the pointer points to it should read the value of the location that the pointer points to.
An example is variables are like houses that hold values. A pointer is like the address on the house. Typically when the compiler reads a pointer it only sees the address. When you put * infront of the pointer it tells the compiler to look inside the "house" to extract the value within. When you assign pointers new addresses you do not want to use the * or else you are copying values and not the addresses.
So what you want to be doing instead is in the setNext for example:
next = newContainer;
Previous answers explain reason of segmentation fault. Anyway if you need that sample for academic use, then IMHO you forgot about initialization of class members. The second issue is memory management - who does alloc/free these objects? In your sample there is nor constructor, neither destructor :)
Your class could look like this one below:
class LinkedListContainer
{
public:
LinkedListContainer()
: d_emp( 0 )
, d_next( 0 )
{
}
bool isValid() const
{
const bool result = ( d_emp != 0 );
return result;
}
const Employee& getEmployee() const
{
assert( isValid() );
return *d_emp;
}
void setEmployee( Employee* emp )
{
d_emp = emp;
}
LinkedListContainer* getNext()
{
return d_next;
}
void setNext( LinkedListContainer* next )
{
d_next = next;
}
private:
Employee* d_emp;
LinkedListContainer* d_next;
};
If you don't want to bother with memory management for Employee objects, then just use shared_ptr from boost library.
typedef boost::shared_ptr< Employee > SmartEmployee;
class LinkedListContainer
{
public:
LinkedListContainer()
: d_next( 0 )
{
}
bool isValid() const
{
return d_emp;
}
const Employee& getEmployee() const
{
assert( isValid() );
return *d_emp;
}
void setEmployee( SmartEmployee emp )
{
d_emp = emp;
}
LinkedListContainer* getNext()
{
return d_next;
}
void setNext( LinkedListContainer* next )
{
d_next = next;
}
private:
SmartEmployee d_emp;
LinkedListContainer* d_next;
};