Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try since a few day to make this little code but it doesn't work. I see a lot of question about this problem but i didn't find an answer to mine.
Here is the code for Voiture.cpp :
#include <iostream>
using namespace std;
#include <string.h>
#include "modele.h"
Voiture::Voiture()
{
Nom=NULL;
setNom("Default");
VoitChoix=Modele();
cout << "COnstructeur default" << endl;
}
Voiture::Voiture(const char* N,const Modele V)
{
Nom=NULL;
setNom(N);
setModele(V);
cout << "COnstructeur initialisation" << endl;
}
Voiture::Voiture(const Voiture& V)
{
Nom=NULL;
setNom(V.getNom());
setModele(V.getModele());
cout << "COnstructeur copie" << endl;
}
Voiture::~Voiture()
{
if(Nom)
{
cout << "Voiture : Destruction de" << Nom << endl;
delete [] Nom;
}
}
Here is the code for Modele.cpp :
#include <iostream>
#include <string.h>
using namespace std;
#include "modele.h"
Modele::Modele()
{
Nom=NULL;
setNom("Default");
Puissance=0;
Diesel=true;
PrixDeBase=0;
cout << "COnstructeur default" << endl;
}
Modele::Modele(const char* N,const int P,const bool D,const float PDB)
{
Nom=NULL;
setNom(N);
setPuissance(P);
setDiesel(D);
setPrixDeBase(PDB);
cout << "COnstructeur initialisation" << endl;
}
Modele::Modele(const Modele& M)
{
Nom=NULL;
setNom(M.getNom());
setPuissance(M.getPuissance());
setDiesel(M.isDiesel());
setPrixDeBase(M.getPrixDeBase());
cout << "COnstructeur copie" << endl;
}
Modele::~Modele()
{
if(Nom)
{
cout << "Modele: Destruction de" << Nom << endl;
delete [] Nom;
}
}
Here is the code for main.cpp :
int main()
{
cout << "(1) ***** Test du constructeur par defaut de Voiture *****" << endl;
{
Voiture voiture;
voiture.Affiche();
}
}
I don't put all the code, just where i have the problem.
Thanks ! :(
One obvious problem is that you're missing a user-defined assignment operator:
VoitChoix=Modele();
This calls the assignment operator, not copy constructor. Since you do not have a user-defined assignment operator for Modele, then you will have issues on destruction of VoitChoix. More specifically, you are assigning all of the values that Modele() has created to VoitChoix.
So you have two instances that have the same pointer value for Nom. When the temporary Modele() goes out of scope, it will call the destructor, thus deleting Nom. When VoitChoix goes out of scope, it will attempt to delete the same pointer value for Nom. Thus the double delete error.
The user defined assignment operator for Modele would have the following signature:
Modele& operator=(const Modele&);
You will need to implement this function before going any further. This can be done easily using the copy/swap idiom: What is the copy-and-swap idiom?
Also, please follow the rule of three when creating your class: What is The Rule of Three?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hello this code is part of a big code and it causing a lot of problem i dont know why. i tried to use structer and vectors its ggot an error about vector out of range then i switched to class but still got same error im now compiling just problematic and its looks like a memory error. how can i fix this ?
#include <time.h>
#include <locale.h>
#include <vector>
#include <exception>
using namespace std;
class işlem {
string işlemdetay; int işlemtutar; time_t işlemtarih; int hesapno;
public:
vector <işlem> işlemler;
işlem() { işlemdetay = " "; işlemtutar = 0; işlemtarih = time_t(0); hesapno = 0; };
işlem(string İşlemdetay, int İşlemtutar, int Hesapno) {
işlemdetay = İşlemdetay; işlemtutar = İşlemtutar; hesapno = Hesapno;
işlem newişlem(işlemdetay, işlemtutar, hesapno);
işlemler.push_back(newişlem);
}
void listele(int hesapid) {
int size = işlemler.size();
for (; size >= 0; size--)
{
if (işlemler[size].hesapno == hesapno)
{
//cout << "İşlem Tarihi: " << işlemler[size].işlemtarih << endl;
cout << "İşlem Tutar: " << işlemler[size].işlemtutar << endl;
cout << "İşlem Detayı: " << işlemler[size].işlemdetay << endl;
}
}
}
};
int main()
{
try
{
işlem newişlem("Hesap oluşturuldu.", 400, 1);
}
catch (const std::exception e)
{
cout << e.what();
}
}```
işlemler[işlemler.size()] is out-of-range. The initial value of size should be işlemler.size() - 1, not işlemler.size().
This question already has an answer here:
Why does this simple C++ code segfault? [closed]
(1 answer)
Closed 3 years ago.
I'm practicing operator overloading, and my goal is to enumerate all the values of a vector class I have written myself.
In doing this I came across a segfault (no biggie) and started to pare back my code to find where it originated. After some difficulty, I've come to a point where I don't understand what's going wrong.
While trying to run a for loop to iterate over the data in a vector object, I found that I get a segfault if I use a variable s which is set to 10. If I use the integer literal 10, it works.
This makes very little sense to me, but then again I'm working with unfamiliar concepts. Any help is appreciated!
Here's an MCVE:
Compile using g++ Q1.cpp vector.h -o Q1
Demo class (Q1.cpp):
#include <iostream>
#include "vector.h"
#define INFO(x) std::cout << "[INFO]: " << x << std::endl;
int main(void) {
// 1- Test the default constructor
INFO(" ---------- Vector 1 ----------");
vector v1;
INFO(v1);
return 0;
}
Vector class (vector.h):
#include <iostream>
#include <string>
class vector {
public:
float size;
float* data;
vector() : vector(0) {}
vector(int s){
size = s;
data = new float[size]();
}
};
std::ostream& operator<<(std::ostream& stream, const vector& obj){
stream << "vector: size(" << obj.size << ")" << "\n";
int s = 10;
for(int i = 0; i < s; ++i){ // problem occurs here, replace s with '10' and it works.
stream << i;
//stream << "data[" << i << "] = " << obj.data[i];
}
}
Your overloaded function needs to return stream.
Also, don't use size_t as a class member name. It's utterly confusing.
You should also delete the data array when the vector is deleted. It now leaks.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a global function void start_menu() which I'm using as an interface.
void start_menu()
{
int x;
cout << " ------------------------------------" << endl;
cout << " WELCOME TO LIBRARY MANAGEMENT SYSTEM" << endl;
cout << "------------------------------------" << endl;
cout << " 1. ABOUT Books " << endl;
cout << " 2. ABOUT Members " << endl;
cout << " CHOOSE:";
cin >> x;
Books MyBooks; //object of books class
do
{
if (x==1)
{
system("cls");
MyBooks.INTR_Books(); //calling function of Books Class
}
};
}
Then, I have class Books{} which I want to be called in global function void start_menu() but when I make an object of Books class, which is defined as Books MyBooks;, the above code gave me this error:
error: 'Books' was not declared in this scope.
This is Books class after the global function void start_menu():
class Books
{
public:
string BookName; //name of the Book
string Auth; //Author of the book
string Trans; // translator of the book
string myArray[20];
int BookCode; // code of the book
int BookNum; // number of copies exist
void INTR_Books(); //show interface related to books
void ADD_BOOK();
void DELETE_BOOK();
void SEARCH();
void SHOW_ALL();
void BR_BOOK();
};
based on comments ,i had undrestood which Booksclass should be called after void start_menu() global function.
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
Can you tell me the difference between the source 1 and 2?
The book says the first one is call by address(pointer) and the second one is call by reference, but i don't exactly get those two sources.
Please explain those sources to me please, thank you in advance.
1.
#include <iostream>
using namespace std;
void absolute(int *a);
void main()
{
int a = -10;
cout << "Value a before calling the main function = " << a << endl;
absolute(&a);
cout << "Value a after calling the main function = " << a << endl;
}
void absolute(int *a)
{
if (*a < 0)
*a = -*a;
}
2.
#include <iostream>
using namespace std;
void absolute(int &a);
void main()
{
int a = -10;
cout << "Value a before calling the main function" << a << endl;
absolute(a);
cout << "Value a after calling the main function" << a << endl;
}
void absolute(int &a)
{
if (a < 0)
a = -a;
}
In terms of what happens at the CPU level, pointers and references are exactly the same. The difference lies in the compiler, it won't let you do a delete on a reference (and there's less typing)
So in your code both functions do the same thing.
This question already has answers here:
What is object slicing?
(18 answers)
Closed 9 years ago.
I have the following setup:
main.cpp:
int main()
{
vector <Tour> tourList;
Tour* tour_ptr;
for (unsigned int i = 0; i < tourList.size(); i++)
{
tour_ptr = &tourList[i];
tour_ptr->display();
}
}
Tour.h:
class Tour
{
public:
virtual void display();
};
Tour.cpp:
void Tour::display()
{
cout << "Tour ID: " << getID() << "\n";
cout << "Description: " << getdescription() << "\n";
cout << "Tour Fee: $" << getfee() << "\n";
cout << "Total Bookings: " << getbookings() << "\n\n";
}
GuidedTour.h:
class GuidedTour : public Tour
{
public:
void display();
};
GuidedTour.cpp:
void GuidedTour::display()
{
Tour::display();
cout << "Max Tour Group Size: " << getMaxTourists() << "\n";
cout << "Tour Guide: " << getGuideName() << "\n";
cout << "Tour Date: " << getTourDate() << "\n\n";
}
GuidedTour inherits from the Tour class, and I've specified the display() function as virtual in the base Tour class, but for some reason, the GuidedTour display() function never gets called, only the base function gets called every time. What am I doing wrong?
Your code actually doesn't print anything as the std::vector would initially be empty. Other than that, your problem is caused by object slicing (I'm assuming that you are push_back()ing GuidedTours into the vector).
When object slicing takes place, you are storing only the Tour part of your GuidedTour object(s), and that's the reason why you are seeing the output of Tour::display().
To solve your problem, you need to store the objects polymorphically, by using (smart) pointers and dynamically-allocating your objects.
int main()
{
vector <std::unique_ptr<Tour>> tourList;
for(...) {
tourList.push_back(std::make_unique<GuidedTour>(/* constructor parameters */));
...
tourList.push_back(std::make_unique<Tour>(/* constructor parameters */));
}
for (unsigned int i = 0; i < tourList.size(); i++)
{
tourList[i]->display();
}
}
Notice that I am using std::unique_ptr/std::make_unique and not raw newed pointers. Using them would greatly ease you of the problem of manually managing and deleteing your objects, which sometimes[understatement] are the cause of bugs and undefined behavior.
Note that some people might suggest you to use boost::ptr_vector or something similar. Listen to them, especially if they give you arguments on why they are better than the alternatives.
Your problem has nothing to do with your classes, rather how you are creating the object. Each element in the tourList vector is a tour, and nothing at compile time or runtime is there to determine that they are GuidedTours. In effect, GuidedTour is never called, because I don't see a GuidedTour object in your main anywhere.
I am agree with "It'sPete". because you haven't used the GuidedTour class. It will work if you use the following method.
int main()
{
vector <GuidedTour> tourList;
Tour* tour_ptr;
for (unsigned int i = 0; i < tourList.size(); i++)
{
tour_ptr = &tourList[i];
tour_ptr->display();
}
}