Constructor not working correctly with parameters

Hello everyone, I am writing a code for a class that needs to have a constructor that is the starting values. For some reason when i have parameters in constructor I get an error and I do not know why. If anyone can tell me how to fix this i would appreciate it.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  class Rover{
    
private:
    
    string name;
    int xpos;
    int ypos;
    string direction; //Use Cardinal Directions (N,S,E,W)
    int speed; //(0-5 m/sec)
    
public:
    //Constructors
    //defaultRover();
    Rover();
    
    //Get functions
    string getName()const;
    int getXpos()const;
    int getYpos()const;
    string getDirect()const;
    int getSpeed()const;
    void getRoverData();
    
    //Set functions
    void setName(string);
    void setXpos(int);
    void setYpos(int);
    void setDirect(string);
    void setSpeed(int);
 };   
    //Constructor function

 Rover::Rover(int x,int y,string direct, int spd)
    {
        cout<<"Please enter the starting X-position: ";
        cin>>x;
        cout<<"Please enter the starting Y-position: ";
        cin>>y;
        cout<<"Please enter the starting direction (N,S,E,W): ";
        cin>>direct;
        cout<<"Please enter the starting speed (0-5): ";
        cin>>spd;
        
        xpos=x;
        ypos=y;
        direction=direct;
        speed=spd;
        
        cout<<endl; 
    }
Hi,

You are missing a declaration of that constructor in your class definition.

So on line 15, you need:

Rover(int x,int y,string direct, int spd);

But the parameters aren't needed: you ask for input then assign values to member variables.

Normally a constructor like that would have the parameters, not ask for input (do that elsewhere), and set the member variables via a member initialisation list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 Rover::Rover(const std::string& name,  // make sure to init all member variables
                    const int x,  // parameters are const if we aren't changing them
                    const int y,
                    const std::string& direct,  // pass containers by reference
                    const  int spd)
     :  // colon introduces member initialisation list
      name(name),
      xpos(x),  // direct initialisation more efficient than assignment
      ypos(y),  // assignment causes construction of temporaries & copying
      direction(direct), // then direct initialisation
      speed(spd)
    {
        // do validation here 
    }
Topic archived. No new replies allowed.