how call function in second class from first class?

So i know that if i declare two classes i can call the functions in the first class from the second class but how do i call functions in the second class from the first?

so like this

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
#include <iostream>

class class1 
{
public:

	void f1() {
		qClass2.f2();
	}

} qClass1;

class class2 
{
public:

	void f2() {
		std::cout << "this should print";
	}

} qClass2;

int main() {
	qClass1.f1();
	std::cin.ignore();
}
Last edited on
First, why do you use global variables? There are usually better alternatives.

The problem in the current code is that by the line 8, the compiler has not been told yet anything about identifier "qClass2". It does not know the type if the identifier, nor whether that type has members.

You could create a thousand objects of type class1, but your current implementation would make them all call a member of one particular global object of type class2. That is awfully restrictive. Granted, class2::f2() does refer to single global object too, but std::cout is very special.
as for the global variables its the only way ive ever been able to get my programs to work. if i declare my instances in the top of the main function like i see in most examples the program never works right. i know this is something i need to learn its just that i have things higher on my priority list atm is all. i mean you see im having scope problems right now even with them declared at the global level.
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
#include <iostream>

class class2; // forward declaration

class class1 
{
public:
  void f1( const class2 & ) const;
};

class class2 
{
public:
  void f2() const;
};

int main()
{
  class2 qClass2;
  class1 qClass1;
  qClass1.f1( qClass2 );
  std::cin.ignore();
  return 0;
}

// Class member implementations
void class1::f1( const class2 & foo ) const
{
  foo.f2();
}

void class2::f2() const
{
  std::cout << "this should print";
}
thanks
Topic archived. No new replies allowed.