-2

I am pursuing some interest in c++ programming by way of self instruction. I am working on some basic stuff for now and am currently having issue getting my classes talking/instantiated?.

I am trying to get my main cpp file to compile alongside a header and call to some class functions through the main using a more efficient command method.

I am stuck and would appreciate some help. I will include both files. I am just trying to get a return value from the header by calling the function.

error: main.cpp:6.21 error: cannot call member function 'void myClass::setNumber(int) without object

the code works when compiled with the main, so it is something with the 'scope resolution operator' i think. First is main.cpp

#include <iostream>

#include "myClass.h"
using namespace std;
int main(){
myClass::setNumber(6);

{
 return number;
}
}

Then my header file myClass.h

// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H


class myClass {

     private:

        int number;//declares the int 'number'
        float numberFloat;//declares the float 'numberFloat


    public:

        void setNumber(int x) {
            number = x;//wraps the argument "x" as  "number"
        }
        void setNumberFloat(float x) {
            numberFloat = x;
        }

        int getNumber() {//defines the function within the class. 

        number += 500;
            return number;
        }
        float getNumberFloat() {//defines the function
        numberFloat *= 1.07;
            return numberFloat;
    }

};

#endif

Any help?

  • 5
    Take a look at [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – molbdnilo Apr 07 '17 at 05:44

1 Answers1

2

The error message says everything:

cannot call member function 'void myClass::setNumber(int)' without object

You need to create an object first:

myClass obj;

then call the class method on that object:

obj.setNumber(6);

The value 6 will get assigned to the number field of the obj variable.

CiaPan
  • 9,381
  • 2
  • 21
  • 35