QUESTION: A CAR Class
Write a class named Car that has the following member variables:
 year. An int that holds the car’s model year.
 make. A string that holds the make of the car.
 speed. An int that holds the car’s current speed.
In addition, the class should have the following member functions.
 Constructor. The constructor should accept the car’s year and make as arguments and assign these values
to the object’s year and make member variables. The constructor should initialize the speed member variable
to 0.
 Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an
object’s year, make, and speed member variables.
 accelerate. The accelerate function should add 5 to the speed member variable each time it is called.
 brake. The brake function should subtract 5 from the speed member variable each time it is called.
Demonstrate the class in a program that creates a Car object, and then calls the accelerate function five times. After
each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function five
times. After each call to the brake function, get the current speed of the car and display it.

Recommended Answers

All 22 Replies

Need full C++ program to the above given question..........

How much are you willing to pay for my time to solve your homework?

Actually it's not a homework i have kept a bet over it with my friend and the bet is if i answered this question he will call me with Sir and if you done that for me i will call you Sir from now onwards and if failed i will have to call him Sir

I guess, when a typhoon is raging over you, the title "Sir" will make all the difference.

please sir need your help

I, and other people her will certainly help you out. The only thing you have to do (do it together with your friend perhaps) is show us some effort on your side. What have you done? What are the problems you encountered? Show us some code. etc.

Ok

#include <iostream>
#include <cstdlib>
#include <string> 



           using namespace std;
                                                                                                        class Car{


                //private member


      private:

             int yearModel;

             string Make;

             int Speed;          


           //public mambers  

      public:

             Car(int, string, int);



             void setModel(int);

              int getModel(void);



             void setMake(string);

             string getMake();


             void setSpeed(int);

             int getSpeed(void);

(i have done uptill this step and as i am new in it don't know how to use consurctor and some other step)

#ifndef CAR_H
#define CAR_H
class Car
{
    private:
        int year_;
        std::string make_;
        int speed_;
    public:
        explicit Car(){}
        explicit Car(int year, std::string make):year_(year),make_(make){ speed_= 0;}
        int getYear()
        {
            return year_;
        }
        std::string getMake()
        {
            return make_;
        }
        int getSpeed()
        {
            return speed_;
        }
        void Accelerate()
        {
            speed_ +=5;
        }
        void Brake()
        {
            speed_ -= 5;
        }
};

#endif

Car.cpp

#include <iostream>

#include "Car.h"

using namespace std;
int main()
{
    Car c(2001,"toyota") ;

    for(int i=0 ; i < 5; ++i)
    {
    c.Accelerate();
    cout << c.getSpeed() << endl;
    }
    for(int i=0 ; i < 5; ++i)
    {
    c.Brake();
    cout << c.getSpeed() << endl;
    } 

}
commented: please tell me whether both of the programs are separate or this is one pograme +0

The first thing that I would suggest is for you to use some comments stating what everything is and what is is supposed to do and maybe some pre and post condition statements around the class methods. Look, I don't want to do your assignment or anything, but here is a different class which you can look at and (maybe) learn something from about how you might be able to write a C++ class of your own. The process is really pretty straight forward for many things. You define the class in the class definition and you declare the instance variables and the methods. After that you define the methods just like any other C++ user-defined method with the exception of using this syntax--> ClassName::MethodName(); You have to resolve the method to the class. You could alternatively just define the method within the class after its declaration, but that would leave you with a cluttered mess for a class definition (at least in my opinion). Anyway, below you will find a very simple C++ class that you can look at and see how to implement methods, constructors, destructors and copy constructors--this is just the tip of the iceberg though and there is a whole lot more so if you really want to learn then you should get a book or two and read up on it.

// Apartment.cpp : Defines the entry point for the console application.
//
// An Example C++ class that defines an Apartment in some ways
//

#include "stdafx.h" // C++ Terminal
#include <iostream> // I/O
#include <string> // string functions
#include <iomanip> // setw()
#include <conio.h> // _getch()

using namespace std;

/*******************************************
******APARTMENT CLASS DEFINITION************
*******************************************/

class _Apartment
{
private:
    char rm_num[4]; // 3 numbers + 1 for '\0'  (C-String)
    float rent;    // monthly rent 
    char* renter;  // variable length char* (string) to hold renter's name
    int occupants; // number of total occupants

public:
    _Apartment(char[], float, char*, int); // 4 argument constructor
    const char* Display_Room_Num(); // display (don't return) the room number
    float Get_Rent() const; // return the rent
    const char* Display_Renter(); // display (don't return) the renter's name
    int Get_Occupants() const; // return the number of occupants
    int Alter_Rent(float); // change the current rent
    ~_Apartment(); // destructor
    _Apartment(_Apartment&); // copy constructor

};// end of _Apartment class definition

/***********************************************
********APARTMENT CLASS METHOD DEFINITIONS******
***********************************************/

_Apartment::_Apartment(char rm_num_par[], float cost = 0, char* name = '\0', int residents = 0){

    strcpy_s(rm_num, rm_num_par); // copy the parameter to the class instance variable
    rent = cost; // parameter 2 = rent

    if(name != '\0'){ // was a name passed or are we using a NULL pointer?
        renter = new char[strlen(name)+1]; // heap memory allocation for variable name length
        strcpy_s(renter, (strlen(name)+1), name); // copy parameter to class variable
    }else{
        renter = new char[24]; // default space allocation if no parameter passed
        renter = " ***NO NAME ENTERED*** "; // give a default value
        renter[23] = '\0'; // make it act like a C-String
    }//end if-else name setting statement

    occupants = residents; // copy parameter 4 over to the class instance variable

}// end 4 argument constructor for _Apartment::
// Post Conditions:         rm_num = rm_num (parameter 1 value) (REQUIRED)
//                          rent = cost (parameter 2 value) (OPTIONAL: Default = 0)
//                          renter = name (parameter 3 value) (OPTIONAL: Default = NULL)
//                          occupants = residents (parameter 4 value) (OPTIONAL: Default = 0)


const char* _Apartment::Display_Room_Num(){ // ACCESSOR METHOD

    for(unsigned short x = 0; x < (strlen(rm_num)); x++){

        cout << rm_num[x]; // print the name out

    }//end room number printing 'for'

    return " "; // return a dummy value because number is printed already...

}// end of _Apartment::Display_Room_Num()

float _Apartment::Get_Rent() const{ // ACCESSOR METHOD

    return rent; // access-return the rent value

}// end of Get_Rent()

const char* _Apartment::Display_Renter(){ //ACCESSOR METHOD

    for(unsigned short x = 0; x < (strlen(renter)); x++){

        cout << renter[x]; // display the renter's name through a loop

    }// end of name displaying 'for' loop

    return " "; // return a dummy value now because display is already done

}// end Display_Renter()

int _Apartment::Get_Occupants() const{ // ACCESSOR METHOD

    return occupants; // return occupants by value

}// end Get_Occupants()

int _Apartment::Alter_Rent(float new_rent) { // MUTATOR METHOD

    if(new_rent >= 0){
        rent = new_rent;
        return 0; // 0 is the success signal
    }else{
        return -1; // -1 is the failure signal
    }// end positive rent check

}// end of Alter_Rent()


_Apartment::~_Apartment(){ // DESTRUCTOR

    renter = 0; // make the char* a NULL pointer
    delete renter; // garbage collection on the heap

}// End of ~_Apartment()

_Apartment::_Apartment(_Apartment& apt_ref){// COPY CONSTRUCTOR

    strcpy_s(rm_num, apt_ref.rm_num); // room number (C-String)

    if(apt_ref.renter != '\0'){// if a Renter name exists
        renter = new char[strlen(apt_ref.renter)+1]; // allocate some heap memory
        strcpy_s(renter, (strlen(apt_ref.renter)+1), apt_ref.renter); // copy value over
    }else{
        renter = new char[24]; // default space allocation if no parameter passed
        renter = " ***NO NAME ENTERED*** "; // give a default value
        renter[23] = '\0'; // make it act like a C-String
    }// end name checking if-else statement

    rent = apt_ref.rent; // rent value
    occupants = apt_ref.occupants; // occupant number value

}// End of _Apartment(_Apartment&)
// Post Conditions:    ALL new object instance variables == the object being copied from
//  I.E.    _Apartment rm2 = rm1;    rm2 now has every variable == rm1
//



/****************************************
**************main()*********************
****************************************/

int _tmain(int argc, _TCHAR* argv[])
{

    // use the constructor--> instantiate an object
    _Apartment room245("245", 250.99, "Joe Smegma", 1);

    // use the other class methods now
    cout << endl << endl << "The rent is: " << room245.Get_Rent();
    cout << endl << endl << "The renter is: ";
    room245.Display_Renter();
    cout << endl << endl << "The Apartment Number is: ";
    room245.Display_Room_Num();
    cout << endl << endl << "The current number of occupants is: " << room245.Get_Occupants();
    cout << endl << endl << "Thanks for using our Apartment system...";

    cout << endl << endl << "Press enter to exit...";
    char x = _getch();


    return 0;
}

The first thing that I would suggest is for you to use some comments stating what everything is and what is is supposed to do and maybe some pre and post condition statements around the class methods.

Note that your sample class is a fine example of how not to comment. Comments supplement the code to answer questions a reader might have like why?. Comments shouldn't simply repeat what the code clearly says, but a plain English comment of obtuse code that cannot be simplified for one reason or another (hey, that's another comment!) are acceptable.

My opinion is that you can never, ever have too many program comments or step comments and a program with too many comments is much easier to debug, use, understand and share than one with not enough comments. And just FYI, the poster here was asking for some help understanding about a simple C++ class so (obviously) it would help him to have too many rather than too few comments to explain the code; right? I always write too many comments in all my code and that way I can always go back and find and change something easily by finding a line of code or by looking for what it does with <Ctrl + F>. Anyway, if you don't think comments are good then that is a great opinion for you, but for me I like to have as many comments as possible because I don't believe that such a thing exists as a program with too many comments.

My opinion is that you can never, ever have too many program comments or step comments and a program with too many comments is much easier to debug, use, understand and share than one with not enough comments.

I strongly disagree. Excessive useless comments can be even worse than no comments.

it would help him to have too many rather than too few comments to explain the code; right?

That's fine, provided it's clear that the unusually verbose comments are being used to help a beginner understand things that would be obvious to everyone else.

Anyway, if you don't think comments are good then that is a great opinion for you

Way to completely misinterpret what I said. I love comments, they're awesome. But there's a condition that the comments must actually be helpful when reading code. For example:

void hello() // function called hello that returns void
{
    cout << "Hello, world!\n";
} // End foo

Both comments are unnecessary. The first just says what anyone with even a passing knowledge of C++ would know from glancing at the code, and the second is so close to the start of the function that the purpose of an end marker is completely defeated.

I don't believe that such a thing exists as a program with too many comments.

I've had to maintain code bases with too many comments. "Too many" meaning all kinds of comments that are utterly useless for understanding and maintaining the code. If the comments provide useful information that cannot be easily gleaned from the code itself, then there's no such thing as "too many". But if the code you posted is indicative of your usual code, I'd call that "too many".

#include <iostream>
#include <math.h>

using namespace std;

class Car
{
private:
int YearModel;
int Speed;
string Make;
public:
Car(int, string, int);
string getMake();
int getModel();
int getSpeed();
void Accelerate();
void Brake();
void displayMenu();
};

Car::Car(int YearofModel, string Makeby, int Spd)
{
YearModel = YearofModel;
Make = Makeby;
Speed = Spd;
}

string Car::getMake()
{
return Make;
}
//To get the year of the car.
int Car::getModel()
{
return YearModel;
}
//To holds the car actual speed.
int Car::getSpeed()
{
return Speed;
}
//To increase speed by 5.
void Car::Accelerate()
{
Speed = Speed + 5;
}
//To drop the speed of the car by 5.
void Car::Brake()
{
Speed = Speed - 5;
}

void displayMenu()
{
cout <<"\n Menu\n";
cout << "----------------------------\n";
cout << "A)Accelerate the Car\n";
cout << "B)Push the Brake on the Car\n";
cout << "C)Exit the program\n\n";
cout << "Enter your choice: ";
}

int main()
{
int Speed = 0; //Start Cars speed at zero.
char choice; //Menu selection

cout << "The speed of the SUV is set to: " << Speed <<endl;
Car first( 2003, "Hyundai", Speed);

//Display the menu and get a valid selection
do
{
displayMenu();
cin >> choice;
while(toupper(choice) < 'A' || toupper(choice) > 'C')
{
cout << "Please make a choice of A or B or C:";
cin >> choice;
}

//Process the user's menu selection
{
switch (choice)
{
case 'a':
case 'A': cout << "You are accelerating the car. ";
cout << Accelerate(first) << endl;
break;
case 'b':
case 'B': cout << "You have choosen to push the brake.";
cout << Brake(first) << endl;
break;}
}
}while (toupper(choice) != 'C');

return 0;
} 

i have done this "car.class" programe by my own now i want the programe in one other code but please keep it mind the output should remain the same as mentioned in the question as well and the programe shoul be executeable and should be error free

Member Avatar for iamthwee

keep it mind the output should remain the same as mentioned in the question as well and the programe shoul be executeable and should be error free

You keep making requests on what YOU are supposed to do.

Member Avatar for iamthwee

@jamblaster, consider learning the language first before giving out bad advice.

I notice a lot of people on here only have negative and completely unproductive and unhelpful comments which have nothing to do with answering the question asked. I wish I was an expert at everything, but who was also a conceited and unhelpful person with a rude and ambiguously narcissistic personality, but I guess I'm not as lucky as some so I guess my advice isn't as good as some (who offer no advice at all, but negative and worthless comments). Anyway, it doesn't surprise me that posts sit on the top page here for days because of the helpful people who like to offer (non) advice and negative (worthless) commentary.

Member Avatar for iamthwee

Relax it wasn't an attack on yourself. Don't take it so personally, I simply stated you shouldn't be offering advice. This happens to be a fact. Just like the grass is green, the sky is blue... All facts.

@Jamblaster: It has often alot to do with how an OP poses his question.

a) I have trouble with my "fump" procedure in my "climr" class. I want a correct solution as quickly as possible!

b) In my "climr" class, I have a problem with my "fump" procedure on line 13 I get an exeption. Could you please have a look. Any answer will be appreciated.

I would you not be more gently with question b, than with question a, wouldn't you?

My Acceleration and Brake cout statements in line 86 & 90 has an error saying that they are undefined. How do i fix this problem?

Instead of adding to an old dead post, you should make a new one and include the code you're referring too. There are probably 3 or 4 or more snippets of code in this post. It is almost impossible to tell which one if any you're talking about. Also if someone else has a similar problem to you, answering it here means that their search won't find the answer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.