C++ Class understanding HI, I\'m trying to understand how to create and use clas
ID: 662260 • Letter: C
Question
C++ Class understanding
HI, I'm trying to understand how to create and use class objets. Please run my code , analyse it and tell me what is really wrong with it. And how to avoid such Error.
When i run it, I have this Error message:" Run -time check failure#3: The variables weig, heig ,ag are being used without being initialized "
And my constructor is not working. i want to understand why all this is happening.
My Code: Just copy it and try it .Thanks
#include <iostream>
#include <string>
using namespace std;
class personType
{
public:
personType();
void setData(string , int, double, double) ;
string printName()const ;
int printAge() const;
double printWeight() const;
double printHeigh() const ;
private:
string name ;
int age ;
double weight ;
double heigh ;
};
int main()
{
string nom ;
int ag ;
double weig , heig ;
personType person ;
cin>> nom,ag,weig,heig ;
person.setData(nom,ag,weig,heig) ;
cout<< person.printName() <<endl;
cout<< person.printAge() <<endl;
cout<< person.printHeigh() <<endl;
cout<< person.printWeight() <<endl;
system("pause") ;
return 0;
}
//CONSTRUCTOR DEFINITION
personType::personType()
{
name ="" ;
age = 0 ;
weight = 0.0 ;
heigh = 0.0;
}
//CLASS FUNCTION DEFINITION
void personType::setData(string n, int a, double w, double h)
{
name = n ;
age = a ;
weight = w ;
heigh = h;
}
string personType::printName() const
{
return name ;
}
int personType::printAge() const
{
return age ;
}
double personType::printWeight() const
{
return weight ;
}
double personType::printHeigh() const
{
return heigh ;
}
Explanation / Answer
Every thing is correct except the reading variables from console(Error is given bold please check)
#include <iostream>
#include <string>
using namespace std;
class personType
{
public:
personType();
void setData(string , int, double, double) ;
string printName()const ;
int printAge() const;
double printWeight() const;
double printHeigh() const ;
private:
string name ;
int age ;
double weight ;
double heigh ;
};
int main()
{
string nom ;
int ag ;
double weig , heig ;
personType person ;
cin>> nom>>ag>>weig>>heig ;
person.setData(nom,ag,weig,heig) ;
cout<< person.printName() <<endl;
cout<< person.printAge() <<endl;
cout<< person.printHeigh() <<endl;
cout<< person.printWeight() <<endl;
return 0;
}
//CONSTRUCTOR DEFINITION
personType::personType()
{
name ="" ;
age = 0 ;
weight = 0.0 ;
heigh = 0.0;
}
//CLASS FUNCTION DEFINITION
void personType::setData(string n, int a, double w, double h)
{
name = n ;
age = a ;
weight = w ;
heigh = h;
}
string personType::printName() const
{
return name ;
}
int personType::printAge() const
{
return age ;
}
double personType::printWeight() const
{
return weight ;
}
double personType::printHeigh() const
{
return heigh ;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.