Getting CrtIsValidHeapPointer Error when trying to release memory [C++] - c++

I have an exercise and I need to create an Engine class and a Car class.
Those are parts of my code:
Car.cpp
Car::Car()
{
_engine = new Engine();
_manufacturer = new char[10];
_prod_year = 0;
_color = new char[10];
}
Car::~Car()
{
// Releasing allocated memory
delete[] _manufacturer;
delete[] _color;
delete _engine;
}
void Car::print(void) const
{
(*_engine).print();
cout << "\n" << endl;
cout << "Manufacturer:" << _manufacturer << "\n" << endl;
cout << "Production Year:" << _prod_year << "\n" << endl;
cout << "Color:" << _color << endl;
}
Car.h
class Car
{
Engine * _engine;
char * _manufacturer;
int _prod_year;
char * _color;
public:
/*
* Creates a Car with the default set of attributes.
*/
Car();
virtual ~Car();
inline Engine * GetEngine() { return _engine; }
void SetEngine(Engine * engine) { _engine = engine; }
inline char * GetManufacturer(){ return _manufacturer; }
void SetManufacturer(char * manufacturer){_manufacturer = manufacturer;}
inline int GetProdYear() { return _prod_year; }
void SetProdYear(int prod_year) { _prod_year = prod_year; }
inline char * GetColor() { return _color; }
void SetColor(char * color) { _color = color; }
void print(void) const;
};
Engine.h
class Engine
{
/*
Represents an Engine with the following attributes:
* int Hourse Power
* char * Manufacturer
* int Production Year
*/
int _horse_power;
char * _manufacturer;
int _prod_year;
public:
Engine();
virtual ~Engine();
int GetHorsePower() { return _horse_power; }
void SetHorsePower(int horse_power) { _horse_power = horse_power; }
char * GetManufacturer(){ return _manufacturer; }
void SetManufacturer(char * manufacturer){_manufacturer = manufacturer;}
int GetProdYear() { return _prod_year; }
void SetProdYear(int prod_year) { _prod_year = prod_year; }
void print() const;
};
Exc.cpp
Engine engine;
engine.SetHorsePower(150);
cout << "Current Horse Power: " <<engine.GetHorsePower()<<endl;
char * manufacturer = new char[strlen("VP") +1];
strcpy(manufacturer, "VP");
engine.SetManufacturer(manufacturer);
cout << "Current Manufacturer: " << engine.GetManufacturer() << endl;
engine.SetProdYear(1995);
cout << "Current Production Year: " << engine.GetProdYear() << endl;
cout << "\n ------------- Printing engine details -------------\n" << endl;
engine.print();
Car car;
car.SetEngine(&engine);
cout << "Current Engine: " << endl;
(*car.GetEngine()).print();
char * car_manufacturer = new char[strlen("Toyota") + 1];
car_manufacturer = { "Toyota" };
car.SetManufacturer(car_manufacturer);
cout << "Current Car Manufacturer: " << car.GetManufacturer() << endl;
car.SetProdYear(2010);
cout << "Current Car Production Year: " << car.GetProdYear() << endl;
char * color = new char[strlen("Yellow") + 1];
color = { "Yellow" };
car.SetColor(color);
cout << "Current Car Color: " << car.GetColor() << endl;
cout << "\n ------------- Printing car details -------------\n" << endl;
car.print();
My program is doing ok until it gets to ~Car and then I get "CrtIsValidHeapPointer".
Can someone tell me what I did wrong?
Thx.
SOLUTION
Engine * engine = new Engine;
engine->SetHorsePower(150);
cout << "Current Horse Power: " << engine->GetHorsePower()<<endl;
char * manufacturer = new char[strlen("VP") +1];
strcpy(manufacturer, "VP");
engine->SetManufacturer(manufacturer);
cout << "Current Manufacturer: " << engine->GetManufacturer() << endl;
engine->SetProdYear(1995);
cout << "Current Production Year: " << engine->GetProdYear() << endl;
cout << "\n ------------- Printing engine details -------------\n" << endl;
engine->print();
Car car;
car.SetEngine(engine);
cout << "Current Engine: " << endl;
car.GetEngine()->print();
char * car_manufacturer = new char[strlen("Toyota") + 1];
strcpy(car_manufacturer, "Toyota");
car.SetManufacturer(car_manufacturer);
cout << "Current Car Manufacturer: " << car.GetManufacturer() << endl;
car.SetProdYear(2010);
cout << "Current Car Production Year: " << car.GetProdYear() << endl;
char * color = new char[strlen("Yellow") + 1];
strcpy(color, "Yellow");
car.SetColor(color);
cout << "Current Car Color: " << car.GetColor() << endl;
cout << "\n ------------- Printing car details -------------\n" << endl;
car.print();
return 0;

In the Car constructor you dynamically allocate an Engine and assign to _engine.
Then in your main program you do
car.SetEngine(&engine);
thereby changing _engine to point to an object you haven't allocated dynamically with new, and losing the original pointer and giving you a memory leak.
So in the Car destructor you try to delete a pointer you haven't allocated with new leading to undefined behavior.
There are also problems with the strings, where you do thing like
char * car_manufacturer = new char[strlen("Toyota") + 1];
car_manufacturer = { "Toyota" };
That first allocates memory, and you assign a pointer to that memory to car_manufacturer. Then directly afterward you make car_manufacturer point somewhere else again losing the pointer to the memory you have allocated and a new memory leak. Besides you then make set the pointer in the car object to the string literal "Toyota" which again is a pointer to memory you have not allocated with new[] so doing delete[] again leads to undefined behavior.
Solving the problem with the strings are easy, even if you don't want to use std::string (which is the recommended solution), and that is to copy the string instead of reassigning the pointer:
char * car_manufacturer = new char[strlen("Toyota") + 1];
strcpy(car_manufacturer, "Toyota");
To solve the first problem with the engine, you need to allocate the new engine dynamically too, if you have to call SetEngine.
In your Set function you should also free the memory already allocated, so you don't have memory leaks.

Related

Shapes and their point ids. Shape ids are different but point ids are consecutively incremented

Requirement:
Shape ID: 0 (say rectangle)
Point IDs in rectangle: 0, 1, 2 and 3.
Shape ID: 1 (say square)
Point IDs in square: 0, 1, 2 and 3.
I wrote a code by for creating a shape and adding points to each shape. Classes Shape and LBP are defined.
Problem:
The point IDs are not starting from '0' in shape 1. Ideally, the point IDs in shape 1 (square )should start from 0 rather than 1. I feel that is the program appending the newly created point to the point set of the previous shape object i.e. shape 0 (rectangle).
Shape ID: 0 (say rectangle)
Point IDs: 0
Shape ID: 1 (say square)
Point IDs: 1
Question: How to make the point ids start from '0' for every new shape created?
The classes defined are as shown below.
MasterDefine.h
#include<iostream>
using namespace std;
class LBP
{
private:
double x, y;
int pointID;
static int pointCount;
public:
void setLBP(double, double);
void getLBP(double&, double&);
void addLBPatEnd();
void addLBPatLocation();
void delLBPatEnd();
void delLBPatLocation(int);
void setLBPID();
int getLBPID();
void goToNode(int);
int getNoOfPoints();
LBP(double, double);
~LBP();
LBP* next, * prev;
};
class Shape
{
private:
int shapeID;
static int shapeCount;
public:
void setShapeID();
int getShapeID();
LBP* points;
Shape();
};
Main.cpp
#include"MasterDefine.h"
int LBP::pointCount = 0;
int Shape::shapeCount = 0;
LBP* lbp, *firstPt, *lastPt;
void printLBPForward();
void printLBPReverse();
void delLBP(int);
void delAllLBPs();
int main()
{
cout << endl << "Hello world" << endl;
Shape* shape0 = new Shape;
cout << endl << "Shape id is " << shape0->getShapeID() << endl; //gives id of shape0
LBP* s0p0 = new LBP(22, 33); //point 0 of shape 0
shape0->points = s0p0;
Shape* shape1 = new Shape;
cout << endl << "Shape id is " << shape1->getShapeID() << endl; //gives id of shape1
LBP* s1p0 = new LBP(10, 5);//point 0 of shape 1
shape1->points = s1p0;
cout << endl << "point id is " << s1p0->getLBPID() << endl;
return 1;
}
LBP.cpp
#include"MasterDefine.h"
//#include "LBP.h"
LBP* lbpFirst, *lbpLast;
void LBP::getLBP(double& getX, double& getY)
{
getX = x;
getY = y;
}
void LBP::addLBPatEnd()
{
// cout << endl << "add lbp at end " << endl;
// cout << endl << "Pointer value in member function " << this << endl;
LBP* tempNode;
if (getNoOfPoints() == 1)
{
tempNode = this;
tempNode->next = NULL;
tempNode->prev = NULL;
lbpFirst = tempNode;
}
if (getNoOfPoints() == 2)
{
tempNode = this;
lbpFirst->next = tempNode;
lbpFirst->prev = tempNode;
tempNode->next = tempNode->prev = lbpFirst;
lbpLast = tempNode;
}
if (getNoOfPoints() > 2)
{
tempNode = this;
lbpLast->next = tempNode;
tempNode->next = lbpFirst;
lbpFirst->prev = tempNode;
tempNode->prev = lbpLast;
lbpLast = tempNode;
}
//goToNode();
}
void LBP::delLBPatEnd()
{
LBP* tempNodeDel;
tempNodeDel = lbpFirst;
do
{
tempNodeDel = tempNodeDel->next;
} while (tempNodeDel->getLBPID() != pointCount - 2);
cout << endl << "tempNodeDel id is " << tempNodeDel->getLBPID() << endl;
tempNodeDel->next = lbpFirst;
lbpFirst->prev = tempNodeDel;
}
void LBP::delLBPatLocation(int NodePos)
{
LBP* TempNodePosDel, *TempNodePosDelPrev, *TempNodePosDelNext;
TempNodePosDel = lbpFirst;
do
{
TempNodePosDel = TempNodePosDel->next;
} while (TempNodePosDel->getLBPID() != NodePos);
cout<<endl<<"NodeID that is to be deleted is "<<TempNodePosDel->getLBPID()<<endl;
cout << endl << "TempNodePosDel" << TempNodePosDel << endl;
TempNodePosDelPrev = TempNodePosDel->prev;
TempNodePosDelNext = TempNodePosDel->next;
cout << endl << "TempNodePosDelPrev id is " << TempNodePosDelPrev->getLBPID() << endl;
cout << endl << "TempNodePosDel id is " << TempNodePosDel->getLBPID() << endl;
cout << endl << "TempNodePosDelNext id is " << TempNodePosDelNext->getLBPID() << endl;
TempNodePosDelPrev->next = TempNodePosDelNext;
TempNodePosDelNext->prev = TempNodePosDelPrev;
cout << endl << "************************************" << endl;
cout << endl << "TempNodePosDelPrev " << TempNodePosDelPrev << endl;
cout << endl << "TempNodePosDelPrev->next " << TempNodePosDelPrev->next << endl;
cout << endl << "TempNodePosDelNext->prev " << TempNodePosDelNext->prev << endl;
cout << endl << "TempNodePosDelNext " << TempNodePosDelNext << endl;
cout << endl << "************************************" << endl;
}
void LBP::setLBPID()
{
pointID = pointCount;
}
int LBP::getLBPID()
{
return pointID;
}
void LBP::goToNode(int)
{
}
int LBP::getNoOfPoints()
{
return pointCount;
}
LBP::LBP(double setX, double setY)
{
x = setX;
y = setY;
setLBPID();
pointCount++;
addLBPatEnd();
}
LBP::~LBP()
{
cout << endl << "In destructor " << endl;
int NodePosForDel;
NodePosForDel = this->getLBPID();
if (NodePosForDel != 1)
{
delLBPatLocation(NodePosForDel);
}
/*delLBPatEnd();*/
cout << endl << "this pointer in destructor " << this << endl;
pointCount--;
}
Shape.cpp
#include"MasterDefine.h"
void Shape::setShapeID()
{
shapeID = shapeCount;
}
int Shape::getShapeID()
{
return shapeID;
}
Shape::Shape()
{
setShapeID();
shapeCount++;
}
Console output:
Shape id is 0
point id is 0
Shape id is 1
point id is 1
Can anyone help me in this? I am definitely missing something. I can't figure it out.
Question: How to make the point ids start from '0' for every new shape created?
Since your static int pointCount; member is static, it's the same member variable for all instances of class LBP, and because the instances share the member, upon creating a new instance, it has access to the changes made to this variable by all previous instances here:
LBP::LBP(double setX, double setY)
{
...
pointCount++;
...
}
This value is definitely not supposed to be stored statically, and it's neither responsibility of a vertex to store number of all vertices in a shape. Make a non-static variable of class Shape for example and keep that information there:
class Shape
{
private:
size_t verticesNum;
...

C++ Trying to make a method in a class that can deep copy one object to another. Visual studio is not letting me step into the method

It's supposed to allocate all memory dynamically, so I need to use the pointers. I can't troubleshoot because for some reason visual studio won't let me step into the code. I need to make a method to deep copy objects and this is the method in my class to override the = operator.
Trophy& Trophy::operator=(const Trophy& obj){
this->name = new string(*(obj.name));
this->level = new int (*(obj.level));
this->color = new Color (*(obj.color));
return *this;
}
And here's the constructor in case that helps
Trophy::Trophy() {
*name = "";
*level = 0;
*color = BRONZE; }
as well as the private part of the class
private:
string* name = new string;
int* level = new int;
Color* color = new Color;
And here's my main as simple as I could get it. The last two couts should be different if the deep copy works.
Trophy* newTrophy = new Trophy();
newTrophy->setName("My Trophy");
newTrophy->setLevel(10);
newTrophy->setColor(GOLD);
cout << newTrophy->getName() << " " << newTrophy->getLevel() << " " << newTrophy->getColor() << endl;
Trophy* copyTrophy = new Trophy();
copyTrophy = newTrophy;
cout << copyTrophy->getName() << " " << copyTrophy->getLevel() << " " << copyTrophy->getColor() << endl;
newTrophy->setName("Please work");
newTrophy->setLevel(5);
newTrophy->setColor(SILVER);
cout << newTrophy->getName() << " " << newTrophy->getLevel() << " " << newTrophy->getColor() << endl;
cout << copyTrophy->getName() << " " << copyTrophy->getLevel() << " " << copyTrophy->getColor() << endl;

c++ set const char* member variable of class

When I am trying to assign a member variable, which is const char*, it just ends the program.
However, if I get some cin inputs before I assign a member variable, it works.
this is my NameCard.h
class NameCard {
private:
const char* name;
const char* companyName;
const char* phoneNumber;
enum grade{CLERK, SENIOR, ASSIST, MANAGER};
grade my_grade;
NameCard* nextCard;
NameCard* head;
public:
NameCard(const char*, const char*, const char*, int);
void setName();
void setCompanyName();
void setPhoneNumber();
void setMyGrade();
void setHead(NameCard*);
void setNextCard(NameCard*);
void findInfo(char*);
void printAll();
};
This is main.cpp
#include <iostream>
#include <cstring>
#include "NameCard.h"
using namespace std;
NameCard::NameCard(const char* a, const char* b, const char* c, int d){
name = a;
companyName = b;
phoneNumber = c;
switch(d){
case CLERK: my_grade = CLERK; break;
case SENIOR: my_grade = SENIOR; break;
case ASSIST: my_grade = ASSIST; break;
case MANAGER: my_grade = MANAGER; break;
}
cout << name << " " << companyName << " " << phoneNumber << " " << my_grade << endl;
}
void NameCard::setName(){
char* name;
cout << "type name." << endl;
cin >> name;
this->name = name;
cout << this->name << endl;
}
void NameCard::setCompanyName(){
char* company_name;
cout << "type company name." << endl;
cin >> company_name;
this->companyName = company_name;
cout << this->companyName << endl;
}
void NameCard::setPhoneNumber(){
char* phone_number;
cout << "type phone number." << endl;
cin >> phone_number;
phoneNumber = phone_number;
cout << phoneNumber;
};
void NameCard::setMyGrade(){
int input_grade;
cout << "type position. 1)CLERK 2) SENOIR 3) ASSIST 4)MANAGER" << endl;
cin >> input_grade;
switch(input_grade){
case CLERK: my_grade = CLERK; break;
case SENIOR: my_grade = SENIOR; break;
case ASSIST: my_grade = ASSIST; break;
case MANAGER: my_grade = MANAGER; break;
}
cout << input_grade;
};
void NameCard::setHead(NameCard* head){
this->head = head;
};
void NameCard::setNextCard(NameCard* next){
this->nextCard = next;
}
void NameCard::findInfo(char* target_name){
NameCard* temp;
temp = head;
while(temp != NULL){
if(temp->name == target_name){
cout << "name : " << temp->name << endl;
cout << "companyName : " << temp->companyName << endl;
cout << "phoneNumber : " << temp->phoneNumber << endl;
cout << "grade : " << temp->my_grade << endl;
break;
}
temp = temp->nextCard;
}
};
void NameCard::printAll(){
NameCard* temp;
temp = head;
while(temp!= NULL){
cout<< "----------------------------" << endl;
cout << "name : " << temp->name << endl;
cout << "companyName : " << temp->companyName << endl;
cout << "phoneNumber : " << temp->phoneNumber << endl;
cout << "grade : " << temp->my_grade << endl;
temp = temp->nextCard;
}
}
int main(){
int index = 0;
NameCard* head = new NameCard("test", "test", "test", 3);
NameCard* bef = NULL;
// char input[50];
// cout << "nmae ";
// cin >>input;
head->setName();
head->setPhoneNumber();
head->setCompanyName();
head->setMyGrade();
return 0;
}
And the problem is here. This is not working. The program ends right after it gets name from setName(). It just ends at the setName() cin >> name. it did not print name after then, and stopped.
int main(){
int index = 0;
NameCard* head = new NameCard("test", "test", "test", 3);
NameCard* bef = NULL;
// char input[50];
// cout << "nmae ";
// cin >>input;
head->setName();
head->setPhoneNumber();
head->setCompanyName();
head->setMyGrade();
return 0;
}
However, this is working fine. it gets the test input and executes all the code below.
int main(){
int index = 0;
NameCard* head = new NameCard("test", "test", "test", 3);
NameCard* bef = NULL;
char input[50];
cout << "test input ";
cin >>input;
head->setName();
head->setPhoneNumber();
head->setCompanyName();
head->setMyGrade();
return 0;
}
You are writing to memory you didn't allocate and most likely don't own.
Check this for example
void NameCard::setName(){
char* name;
cout << "type name." << endl;
cin >> name;
this->name = name;
cout << this->name << endl;
}
You declare char* name and try to read from cin into it. But name is just an uninitialized pointer.
One fix may be to declare name as an array, which also decays to a pointer (so it can be used as a pointer), but does have associated memory. Like this
char name[50];
Or if you want it to be dynamically allocated
char* name = new char[50];
// Use it and when you are done delete it
// Never forget to release memory allocated with new or you get a memory leak
delete[] name;
The key point is that the pointer needs to point to some memory block you know you can use. Note that in the example I allocated 50 chars, you have to make sure you never use (read/write) past the allocated memory, or you get the same error you have been getting and potentially program termination.
A safer alternative is to use std::string, which automatically handles memory for you, so you don't have to mind about allocation and releasing.
You could do something like
std::string name;
std::cin >> name;

Having difficulty creating operator overload for class module using literal string as argument

I am relatively new to C++. I am hoping to get assistance creating an overload operator that will permit me to use a literal string with a class I am writing. This project is for learning.
I created a custom Date class (and have not worried about the actual logic in the class; I'm just trying to get the interface working and to understand where my roadblock is.
It may not look like it, but I have put in a lot of time on this, so an explanation designed for a beginning c++ progammer would be very helpful to me and anyone who follows in my footsteps.
Basically, I'd like to be able to do this with my class:
Date dt(5,6,92);//create class object
int myint;
myint = dt;//this works
string mystr;
mystr = dt("mm/dd/yy");//this does not compile
Thanks in advance. (A compilable test program shown below)
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
cout << "Constructor int m, int d, int y called " << endl;
mo = m; da = d; yr = y;
}
string getdatestr(const char *s = "") {//user sends in format "d2/" "mm/dd/yy" etc
cout << "getdatestr const char *s called mo = " << mo << " da = " << da << "yr = " << yr << endl;
return to_string(mo) + "/" + to_string(da) + "/" + to_string(yr);
}
int getdate(){
cout << "getdate int t called" << endl;
string tag;
tag = to_string(yr) + to_string(mo) + to_string(da);
return stoi(tag);
}
string getdate(string &str){
cout << "getdate with string as ref" << endl;
return "5/5/55";
}
int getdate(int &myint){
cout << "getdate with int as ref" << endl;
return 12345;
}
void setdate(string dt){
cout << "setdate string dt called " << dt << endl;
mo = 1;
da = 2;
yr = 2020;
}
void setdate(int intdte){
cout << "setdate int to " << intdte << endl;
mo = 99;//any int for now
da = 98;
yr = 1997;
}
void setdate(const char *dte){
cout << "setdate char* dte = " << dte << endl;
mo = 94;
da = 95;
yr = 1996;
}
~Date(){
cout << "destructor called" << endl;
}
//below code permits this in main(): myint = dt;
operator int() {
cout << "operator int()" << endl;
string tag;
tag = to_string(yr) + to_string(mo) + to_string(da);
return stoi(tag);
}
//end section to permit: myint = dt;
//what do I need so I can do this: mystr = dt("mm/dd/yy");, nothing below worked; I tried many more iterations
//than what are shown here
/*
operator string() {
cout << "operator string char" << endl;
return "hello world";
}
string operator = (string &rhs){
cout << "string" << endl;
return "return a string";
}
operator = (const string &rhs){
cout << "will this work?" << endl;
return *this;
}
char& operator = (char(&)[9]){
cout << "whoa, it worked" << endl;
//return "got it";
}
operator = (char*){
cout << "try again" << endl;
}
string operator const char(&)[9] {
cout << "one more time" << endl;
string *ptr;
ptr = "one more time";
return ptr;
}
//end nothing worked to permit me to do this mystr = dte("mm/dd/yy"); section
*/
};//end of class
int main()
{
//create a Date class object dt
Date dt(5, 6, 92);
dt.setdate("02/15/22");
cout << endl;
cout << "next two mystr messages return null because I " << endl;
cout << "can't seem to write a valid overload operator for a literal string" << endl;
string mystr;
//mystr = dt("mm/dd/yy");//does not compile (no match for call to '(Date) (const char [9])'
cout << "mystr using dt(str) = " << mystr << endl;
string myconv = "mm/dd/yy";
//mystr = dt(myconv);//does not compile (no match for call to '(Date) (std::__cxx11::string&)'
cout << "mystr using dt(mm//dd//yy) = " << mystr << endl;
cout << endl;
//this section works
//can I assign dt to an integer (as #days from a reference date)
cout << "this section seems to work" << endl;
int myint;
cout << "myint = dt;" << endl;
myint = dt;//does not compile
cout << "myint (using = dt;) = " << myint << endl;
cout << endl;
system("pause");
}

Semantic error in the selection condition of the type of LED lamps

I have a class of light bulbs. There are methods and constructors in this class. There is even a destructor) The problem is that I have to determine and display information about class members with type "n" in the TEST() method (LED lamps).
To implement this task, he developed the gettype() method, which returns the type of an object, and, in fact, the TEST() method, which displays information about light bulbs.
The problem is that nothing works for me. I tried a lot of things, but it doesn’t work out for me to implement this task. I'm new to programming (
Code:
#include <iostream>
using namespace std;
class lamp
{
public:
// methods
void TEST(void);
char* gettype (void);
void INIT(void);
void SHOW(void);
// construcrors
lamp();
lamp(const char *t, int powe, const char *c, double cos);
lamp(const lamp & obj);
// destructor
~lamp();
private:
// data
char type[100]; // LED, energy-saving or incandescent lamp
int power; // LED lamp - "n"
char color[100];
double cost;
};
lamp::lamp() {
cout << "This object was created in the default constructor.\n";
strcpy(type, "");
power = 0;
strcpy(color, "");
cost = 0;
}
lamp::lamp(const char *t, int powe, const char *c, double cos) {
cout << "This object was created in the constructor with parameters.\n";
strcpy(type, t); //*t
power = powe;
strcpy(color, c); //*c
cost = cos;
}
lamp::lamp(const lamp & obj) {
cout << "This object was created in the copy constructor.\n";
strcpy(type, obj.type);
power = obj.power;
strcpy(color, obj.color);
cost = obj.cost;
}
lamp::~lamp() {
cout << "Deletion of object by destructor.\n";
}
void lamp::SHOW(void) {
cout << "Lamp Information:\n";
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void lamp::INIT(void) {
cout << "Enter lamp information:\n";
cout << "\nType (if LED, then n) > "; cin >> type;
cout << "\nPower > "; cin >> power;
cout << "\nColor > "; cin >> color;
cout << "\nCost > "; cin >> cost;
}
char* lamp::gettype (void) {
return type;
}
void lamp::TEST(void) {
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void main() {
setlocale(0, "");
// default constructor for 1 class instance
lamp l1;
cout << "Entering data for the first product." << endl;
l1.INIT();
// constructor with parameters for 2 class instances
cout << endl << "Information about the second object: \n";
lamp l2("n", 950, "yellow", 1580);
// copy constructor for the third object
cout << endl << "Information about the third object: \n";
lamp l3(l2);
// Derived information about all the lamps using the method SHOW
l1.SHOW();
l2.SHOW();
l3.SHOW();
// I create an array of two objects using the default constructor
lamp la[2];
I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
for(int i = 0; i < 2; i++) {
la[i].INIT();
}
// I output data from an array of objects using the method SHOW
cout << "Showing items." << endl;
for (int i = 0; i < 2; i++) {
la[i].SHOW();
}
// looking for and displaying information about LED lamps
cout << "Search and display information about LED lamps." << endl;
for (int i = 0; i < 3; i++) {
if (la[i].gettype() == "n") {
cout << endl << " lamp number : " << (i + 1) << endl;
la[i].TEST();
cout << endl;
}
}
system("pause");
}
There are several errors in your code:
strcpy is included in <cstring> which is missed. You need to add it in the beginning:
#include <cstring>
main() function should be declared as int main() and you need to add a return statement
int main() {
//YOUR CODE HERE
return 0;
}
You missed a comment sign at line 104
lamp la[2];
//I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
After fixed, your code should be able to run.