Constructor Overloading

Pages: 12
Now, I get what you want to do:
using default parameters.
The parameters should be initialize in the prototype, and not in the function definition

Here:
vehicle.h:
1
2
3
4
5
6
class vehicle
{
     public:
     vehicle (int numOfWheels = 4, int numofDoors = 4);
     others follow
}


vehicle.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include "vehicle.h"
{
     vehicle::vehicle(int numOfWheels, int numOfDoors)
     {
            numberOfWheels = numOfWheels;
            numberOfDoors = numOfDoors;
     }
     
     others follow......
}

vehicle-test.cpp
#include "vehicle.h"

int main ()
{
         vehicle jaguar;
         vehicle marcoplo(6);
         vehicle Limo(4, 6);

         //All objects will work well now because you have a constructor 
         //with default parameters
}

I trust you can find you way with this vehicle from here. LOOOL
Thanks everyone. Oops ignore the vehicle/Vehicle typo.. sticky fingers.. I am always using 'Vehicle' in the code, but had to type it into the forum manually.


Arkad - I will reimplement using this method - should Vehicle.cpp not have 'class Vehicle' after the include of Vehicle.h ? Should I just use the code as shown in your post above?

I have tried compiling Vehicle.cpp without the class keyword as shown in the code you posted, but it gives:

 
Vehicle.cpp:6: error: expected unqualified-id before '{' token


Many thanks
Last edited on
I have no idea why @Arkad has done it the way he has...
To give you an idea of how a class is normally implemented, here is a basic (unrelated) class so that you can see how it is normally done:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// class.h

// include guards (don't have to call it like this, this is just my way)
#ifndef __CLASS_H_INCLUDED__
#define __CLASS_H_INCLUDED__

class C {
    public:
        C();

        float doSomething(int num);

    private:
        int _num;
};

#endif // __CLASS_H_INCLUDED__ 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// class.cpp
#include "class.h"
#include <iostream>

// now we implement the class

// The function 'C' belong to class/namespace 'C':
C::C() {
    num = 0;   
    // or use initializer lists, this is just an example
}

// The function 'doSomething' belongs to the class 'C':
float C::doSomething(int num) {
    _num += num;
    std::cout << "Number: " << _num << std::endl;
    return _num / 2.0f;
}


Look up some tutorials on classes for some more information.
@NT3 - that's spot on, thanks very much. I have implemented the Vehicle class as you've shown in my header, and then fleshed it out in Vehicle.cpp using the :: operator. That seems nice and simple and easy enough to understand. - Define the class once in the header, and then implement it in the separate .cpp file.

Many thanks
Topic archived. No new replies allowed.
Pages: 12