-
Class for vehicles
Hi everyone, I wanted to write a class allowing a user to enter information about his or her car. I already have an idea of how to write it but for some reason I feel that something is wrong in the way I've written it.
I haven't completed the code since I just started it but I wanted it to take in all of the information (doors, cylinders, and transmission) and output the type of car the user has (suv/sportrscar). I've done it with the doors already just to give you an example.
Please let me know if I'm on the right track or if I will cause a lot of errors if I continue to complete the code this way.
Code:
#include <iostream.h>
class Vehicle
{
public:
Suv();
Sportscar();
private:
int doors;
int cylinders;
int name;
int color;
int transmission;
};
Vehicle::Suv()
{
cout<<" How many doors does the car have? ";
cin>>doors;
if (doors>=4)
cout<<" You are driving an SUV"<<endl;
else
cout<<" You are driving a sportscar"<<endl;
}
Vehicle::Sportscar()
{
cout<<" How many doors does the car have? ";
cin>>doors;
if (doors<4)
cout<<" You are driving a sportscar"<<endl;
else
cout<<" You are driving an SUV"<<endl;
}
int main()
{
Vehicle c;
c.Suv();
c.Sportscar();
return 0;
}
-
Well, I'm pretty new to C++, so I can't help you much. But I did notice one thing. If you have a compiler that's up to the standard then you will get a error about deprecated headers. Simply change
Code:
#include <iostream.h>
to
Code:
#include <iostream>
-SirCrono6
-
Maybe something like this :
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
class Vehicle
{
public:
Vehicle(int, char*);
~Vehicle();
void print();
private:
char *type;
int doors;
};
Vehicle::Vehicle(int d, char *t)
{
doors = d;
int len = strlen(t);
type = new char[len+1];
strcpy(type,t);
}
Vehicle::~Vehicle()
{
delete type;
}
void Vehicle::print()
{
cout << "The " << type << " has " << doors << " doors." << endl;
}
int main()
{
char buf[] = "SUV";
Vehicle c(4, buf);
c.print();
system("PAUSE");
return 0;
}
You might also want to look into inheritance where you have one base class 'vehicular' with a suv and sportcar class that inherit from the base class.
-
For the transmission type, I'd use an enum:
Code:
class Vehicle
{
public:
enum transmission_type = { manual, automatic };
private:
transmission_type transmission;
};