How do call a function in a seperate class?

closed account (367kGNh0)
I made a function in, let's say class X like so. In the X.h I typed:

void func();

In X.cpp
void X::func(){}

And I want to use func(); in class Y, in a method specifically within class Y, but when I do


1
2
3
#include "X.h"
//...
func();


Then it will say func(); is undefined. How do I call a function from one class into another? (I have added #include "Y.h" in class X)
Last edited on
I presume you have:
1
2
3
4
5
6
7
class X {
  // other code
public:
  void func();

  // other code
};


Lets take an example from the tutorial http://www.cplusplus.com/doc/tutorial/classes/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// classes example
#include <iostream>

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {
  width = x;
  height = y;
}

int main () {
  Rectangle rect;
  rect.set_values (3,4); // function call
  std::cout << "area: " << rect.area(); // function call
  return 0;
}

Do note how an object calls its member function.
How do I call a function from one class into another?
You need to pass the object of type X in order to call its members. Unless you make the function static.
Topic archived. No new replies allowed.