Getting Address of Constructed Item/Member in C++ - c++

I'm writing part of a customer database that handles making new customers and selling them items.
In "Customer.h", I have the struct:
struct Customer {
String name;
int bottles;
Customer(String);
Customer(void) { name = "__invalid__"; }
};
I have a class in the file "CustomerDB.h"
class CustomerDB {
private:
Customer* data; // an array of Customer objects (allocated on the heap)
int capacity; // size of the array on the heap
int length; // number of valid customers actually in the array
public:
CustomerDB(void);
There's a constructor, in "CustomerDB.cpp"
Customer::Customer(string name) {
this->bottles = 0;
this->name = name;
}
I create *an object in another function (which is in "CustomerDB.cpp")
Customer& CustomerDB::operator[](string name) {
Customer Customer(name);
return Customer;
And there's an object of CustomerDB:
CustomerDB database; (Which is in another cpp file which handles the purchases).
The string input works. The object is created. There's no issues there.
So I have 2 problems, one of which is because of the other.
I need to make a new non-Local Customer object in this function (stored into the non-Local Database), and
Return the reference to it. But the constructor I just called doesn't give me a reference. It just makes it, as it should.
I'm unintentionally making a local object instead of one that's added to the "main" database. As a result, the reference is nothing useful.
If I try return Customer; it says that "Customer does not refer to a value."
Any help/advice is appreciated.

I need to return the address of this freshly made Customer
No, you need to return a reference to it.
but the constructor I just called
You never call constructors. You declared an object.
doesn't give me an address. How do I find/obtain this new Customer and return its address?
You take the address of an object like this:
return &Customer;
But to return a reference, it's simply:
return Customer;
But this isn't going to work!
You'd be returning a reference to a local variable. It's about to go out of scope, leaving the reference dangling.
So, you need to rethink your choices with this design.

Related

pointer returned to an object turns null after function returns address

I am new to CPP and I am writing a program as an assignment to simulate a train path system that includes destinations and starts using object oriented programming .
I have 2 classes as shown below (there is a a passenger class but it is not relevant ) :
class Train
{
public:
int cooldown_time;
int travel_time;
int time_since_movement;
int id;
class Station *start;
class Station *destination;
vector<Passenger *> current_passengers;
string status;
void add_train(vector<string> commands, vector<Station> stations, vector<Train> &trains)
{
travel_time = stoi(commands[THIRD_PART + 1]);
cooldown_time = stoi(commands[THIRD_PART + 2]);
status = TSTATUS1;
start = station_search(stations, commands[SECOND_PART]); // this is where the problem happens
destination = station_search(stations, commands[THIRD_PART]);
id = stations.size();
}
};
class Station
{
public:
int tuffy_price;
string city_name;
vector<Passenger *> current_passengers;
vector<Train *> current_trains;
int id;
void add_station(vector<Station> &stations, vector<string> &commands)
{
tuffy_price = stoi(commands[THIRD_PART]);
city_name = commands[SECOND_PART];
id = stations.size();
}
};
I have a search function dedicated to finding the start and destination based off a command that user enters for example :the user enters "add_train cityname1 cityname2 <cooldown_time> <travel_time>". my program detects the city names and searches a vector I have named stations with a key that is the city name and returns a pointer (because of the complications in memory behavior in a function , i set it to pointer) to that station-object .
the function is as below :
Station *station_search(vector<Station> stations, string key)
{
Station *dummy;
for (int i = 0; i < stations.size(); i++)
{
if (stations[i].city_name == key)
{
return &stations[i];
}
}
return dummy;
}}
my problem is with my search function's weird behavior , when I debug the program I see the function find the correct station object and return a pointer to it ,but when the execution returns to the constructor function it randomly (maybe not randomly ) turns the first pointer relating to the start station to null and replaces the values inside with garbage ones.
but after the function searches for the destination station it does not do this and the execution is correct.
Could someone explain why this error is occurring?
My guess is that I have not understood local variables and pointer returns well enough and I have committed a rookie mistake somewhere but I don't seem to find it .
PS: I did not include the full code as it's too long I can include it by attaching a file ,comment down if it's necessary.
Station *station_search(vector<Station> stations, string key)
If you take a closer look here, you will see that the stations parameter is passed by value, which means that after this function returns, this stations parameters will get destroyed. It will be no more. It will cease to exist. It will become an ex-parameter.
However this station_search returns a pointer to some value in this vector. Therefore, rules of logic dictate that it will return a pointer to a destroyed object. Attempting to dereference that pointer, in any way, becomes undefined behavior.
Your other class methods receive parameters by reference, so you must already understand the difference between passing parameters by value vs. by reference, so you should simply do the same here.
Here you are passing a copy of the vector, which is destroyed when the function returns. Additionally, if the key is not found an uninitialized pointer is returned.
Station *station_search(vector<Station> stations, string key)
{
for (Station &station : stations)
{
if (stations.city_name == key)
{
// Pointer becomes invalid when you leave.
// Accessing this pointer will cause undefined behavior.
return &station;
}
}
// This would always cause undefined behavior as dummy was not initialized.
return nullptr;
}
You should pass in a reference and initialize dummy:
Station *station_search(vector<Station> &stations, string key)

Function for adding objects to pointer array

I need to add multiple students to the course class but it keeps overwriting the last entry.
I tried to set the address to the object and also using the bracket operator but this causes a memory leak. The problem is with the AddStudent function
class Student {
public:
Student() { name = "unknown"; };
Student(string n) { name = n; };
void Print() { cout << name << endl; };
string GetName() { return name; };
private:
string name;
};
class Course {
public:
Course(int i) {
id=i;
nstudents=0;
capacity=0;
};
void AddStudent(Student s) {
students=&s;
nstudents++;
};
private:
int capacity;
int nstudents;
Student* students;
int id;
};
It only lets me add one student.
"students=&s;" you are taking the address of a copy-by-value variable which becomes dangling after you leave the function. You don't store the students. You have to put a container in it something like std::vector and copy/move your students in it.
So here with a std::vector with copy and move.
class Course {
public:
Course(int i) {
id=i;
};
void AddStudent(const Student& s) {
students.push_back(s);
};
void AddStudent(Student&& s) {
students.push_back(std::move(s));
};
private:
std::vector<Student> students;
int id;
};
You need to allocate memory for your Students array.In your constructor class add : students = new Student[SomeInitialSize] .Also in your add method you need to check if the size of your students is enough to store another student s,and if there is not you need to allocate more memory.
When you add your first student, students is set to point to s inside the AddStudent function. The problem is since s is local to the function, it is destroyed when the function returns. So students is now a dangling pointer pointing to nowhere since the memory it points to is no longer used to store the Student object. In order to keep the memory after the AddStudent function returns, you would have to dynamically allocate it with new, but there are other problems with that.
Let's say you dynamically allocate the memory for the new student. When we add a second student, some more memory will be allocated to store that. That new memory could end up being in a totally different place. Your AddStudent function will set the students pointer to point to the new Student object, but now we've forgotten where the existing student is stored.
So how do we fix this? We could allocate an array of Student objects, leaving extra space for new students. This way, all the students are stored in a contiguous piece of memory, and students will always point to the first object. In our AddStudent function, we would put the new student after the last student we currently have by doing something like students[nstudents] = s, before incrementing nstudents.
The problem with this is that if we exceed the capacity of the array, we would have to allocate a new larger array and copy everything over since we can't expand an existing block of allocated memory. Or you could just make the array fixed sized. But there's a better solution: std::vector.
std::vector is a standard library container that manages the memory for you. You can store your students there and easily add one using push_back. You can learn how to use vectors by asking your instructor, reading a good book, or finding a tutorial online (do note that there are many bad ones out there).

What have I done wrong when coding this array of objects in C++?

I have two classes, PersonnelLists and Employee. I create an instance of PersonnelLists in my main, like so:
int main() {
PersonnelLists example; //Make a personnel list
...
}
PersonnelLists uses a constructor with member initialisation of a list of employees, the number of employees, and the size of the array:
PersonnelLists::PersonnelLists(): List(new Employee[SIZE]), numEmployees(0), arraySize(SIZE){
}
This results in some null empty employees being created (I think?):
Employee::Employee(): employeeNumber(0), name(NULL), department(NULL) {
}
It is at this line that I get an invalid null pointer error.
I am new with C++, fresh off the boat from Java programming. I'm still a novice with pointers, so I'm not quite sure what I'm doing wrong here.
UPDATE:
As requested, here is the class definition of Employee:
#include <iostream>
class Employee {
public:
Employee(); //constructor
Employee(std::string name, std::string deparment);
void Print() const; //Print this employee's details
void setEmployeeNo(int employeeNum);
private:
int employeeNumber;
std::string name;
std::string department;
};
In Java, new Employee[SIZE] creates an array of null references.
In C++, new Employee[SIZE] creates an array of default-constructed instances of Employee. Your default constructor tries to set name and department to NULL. Attempting to initialize a std::string to NULL would give the error you describe.
There's no "null" string in C++, but you could default-construct name and department, which would set them to empty strings:
Employee::Employee(): employeeNumber(0), name(), department() {
Finally, if List can contain a variable number of elements, I would recommend that you use std::vector<Employee> (which is similar to ArrayList<Employee> in Java).
If name and department are std::strings (or a similar string type), then initializing them with NULL (a null character pointer) is invalid.
If I guessed right, you should default-initialize them instead, as:
Employee::Employee(): employeeNumber(0), name(), department() {
}
But we really can't tell without seeing the class definition of Employee.
As others have pointed out, you should use a std::vector instead of an array. That allows you to only
have valid Employee objects in your "list".
I don't know what the actual definitions of your classes are, so it's kind of hard to identify your problem.
But an option in modern C++ of doing that is to use a std::vector<Employee> data member inside PersonnelList class. std::vector can grow dynamically at runtime, using its push_back() method, e.g.
#include <vector> // for std::vector
class Employee
{
....
};
class PersonnelList
{
public:
PersonnelList()
{
// Nothing to do - vector is initialized empty
}
// Get current employee count
size_t Count() const
{
return m_employees.size();
}
// Add a new employee to the personnel
void AddEmployee(const Employee& newEmployee)
{
m_employees.push_back(newEmployee);
}
private:
std::vector<Employee> m_employees;
};
No need to use raw pointers or something similar: robust RAII STL container classes make your code simpler.

C++ Object references in loop cycle

I'm trying to create different objects of the same type using a loop, and then storing a pointer to each specific object in a linked list. The problem is, each time an object is instanciate, its pointer return the same memory adress, wich doesn't allow me to differentiate each individual object in that list.
Any solution to that? Thanks
I have a function with the following:
Data dt(10,10,2010);
int p=0;
ifstream fx;
fx.open("utilizadores.txt",ifstream::in);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha;
string nLugar;
int iD=1;
while(!fx.eof())
{
getline(fx,linha,'\n');
Utilizador* user;
if(linha.find(',')==-1 && linha.size()>1)
{
cout<<"Entrou no vector"<<endl;
string nlugar(linha.substr(0, linha.size()));
nLugar=nlugar;
}
else
{
int inic=0;
int pos=linha.find(',',inic);
string nick(linha.substr(inic,pos-inic));
pos++;
inic=pos;
pos=linha.find(',',inic);
string email(linha.substr(inic,pos-inic));
user=new Utilizador(dt,iD,nick,email);
cout<<&user<<endl;
cout<<user->clone()<<endl;
}
fx.close();
}
The linked list is declared in the class statement
cout<<&user<<endl;
should be:
cout<<user<<endl;
&user is address of local variable Utilizador*, which remains the same. user variable value itself is the pointer you need, and it should be different on every iteration.
This line
cout<<&user<<endl;
prints the address of a pointer to an object. user is itself a pointer to the object you're creating. To print the address of your object, you meant to write
cout<<user<<endl;
Although it'll be a new object each time, the variable user is always in the same place. You can add the value of user to your list, and it will indeed be different each time.
"&user" return address of pointer, that contains references to objects.

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.