Error while trying to use multiple classes with a constructor for a makefile

Question

I'm experimenting with makefiles, but it's not quite working out for me right now. The experiment is simple: a main.cpp that creates a robot with a function sayHello() that outpus "robot says hello" to the terminal. This is the code in my files.

robot.h:

 #include <stdio.h>
    class Robot(){

    public:
            Robot();
    public:
            void sayHello();

    };

robot.cpp

#include "robot.h"

Robot::Robot()
{
void Robot::sayHello(){
        printf("Robot says hello \r\n");
}

};

main.cpp

#include <stdio.h>
#include "robot.h"


Robot robocop();
int main(void)
{
        printf("hello world \r\n");
        robocop.sayHello();
        return 0;
}

the error is as follows:

robot.h:2:13: error: expected unqualified-id before ‘)’ token class Robot(){ ^ main.cpp: In function ‘int main()’: main.cpp:9:10: error: request for member ‘sayHello’ in ‘robocop’, which is of non-class type ‘Robot()’ robocop.sayHello();

I've been trying on this for too long and could use some help. Thanks!


Show source
| class   | c++   | constructor   | makefile   2017-01-07 15:01 3 Answers

Answers ( 3 )

  1. 2017-01-07 15:01

    This has nothing to do with the makefile.

    The class method definitions in robot.cpp are wrong. As written, the sayHello() method is, bizarrely, shoved inside the class's constructor. This is not correct. Each class method, including the constructor, has to be defined separately:

    #include "robot.h"
    
    Robot::Robot()
    {
    }
    
    void Robot::sayHello()
    {
            printf("Robot says hello \r\n");
    }
    
  2. 2017-01-07 16:01

    I've fixed it like this:

    robot.h

    #include <stdio.h>
    class Robot{
    
    public:
            Robot();
    public:
            void sayHello();
    
    };
    

    robot.cpp

    #include "robot.h"
    
    Robot::Robot()
    {}
    
    void Robot::sayHello(){
            printf("Robot says hello \r\n");
    
    
    }
    

    main.cpp

    #include "robot.h"
    
    
    Robot robocop;
    int main(void)
    {
    
            robocop.sayHello();
            return 0;
    }
    

    Thanks for the help!

  3. 2017-01-07 16:01

    Main:

       int main()
    {
    Robot robocop;
    printf("hello world \r\n");
    robocop.sayHello();
    system("pause>nul");
    return 0;
    }
    

    P.S: Be careful when using system(). I used it in this example as it's the quickest, but I'd suggest using something else in the future; should work for this though.

    Header:

    class Robot {
    
    public:
    Robot();
    void sayHello();
    };
    

    Robot.cpp:

    Robot::Robot()
    {
    return;
    }
    void Robot::sayHello() {
        printf("Robot says hello \r\n");
        }
    

    Pretty much as stated above, you had it written incorrectly. I'd suggest watching some tutorials on the basics of C++.

◀ Go back