Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Calling a function from another class

Very new to c++ having trouble calling a function from another class.

Class B inherits from Class A, and I want class A to be able to call a function created in class B.

using namespace std;

class B;

class A 
{

public:

    void CallFunction ()
    {
        B b;
        b.bFunction();
    }

};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }

};

It all looks fine on screen (no obvious errors) but when I try to compile it i get an error C2079 'b' uses undefined class B.

I've tried making them pointers/ friends but I'm getting the same error.

like image 657
CM99 Avatar asked Jan 05 '13 15:01

CM99


People also ask

How do you call a function from one class from another class in C++?

Class B inherits from Class A, and I want class A to be able to call a function created in class B. using namespace std; class B; class A { public: void CallFunction () { B b; b. bFunction(); } }; class B: public A { public: virtual void bFunction() { //stuff done here } };

How do you call a method from one class to another in C#?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.


1 Answers

class B is only declared but not defined at the beginning, which is what the compiler complains about. The root cause is that in class A's Call Function, you are referencing instance b of type B, which is incomplete and undefined. You can modify source like this without introducing new file(just for sake of simplicity, not recommended in practice):

using namespace std;

class A 
{
public:

    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    {
        //stuff done here
    }
};


 // postpone definition of CallFunction here

 void A::CallFunction ()
 {
     B b;
     b.bFunction();
 }
like image 104
Hui Zheng Avatar answered Oct 03 '22 17:10

Hui Zheng