Umesh Moghariya
Umesh Moghariya

Reputation: 3183

Call a member function of other Class

I have 2 classes.

Class A
{
  void printMe();
}

cpp File:

A::printMe(){
   cout<<"yay";
 }

Class B
 {
    void DoSomething();
 }

cpp File

 B::DoSomething(){

    A::printMe();
 }

How do I make an object of Class A in Class B and use it for the function printMe();

References, but the answers are not accepted and they did not work for me HERE

Upvotes: 0

Views: 75

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

First you'll need to correct the many syntax errors:

// A.h
class A {    // not Class
public:      // otherwise you can only call the function from A
    void printMe();
};           // missing ;

// B.h
class B {    // not Class
public:      // probably needed
    void DoSomething();
};           // missing ;

// A.cpp
#include "A.h"       // class definition is needed
#include <iostream>  // I/O library is needed (cout)

void A::printMe() {        // missing return type
    std::cout << "yay\n";  // missing namespace qualifier
}

// B.cpp
#include "A.h"       // class definitions are needed
#include "B.h"

void B::DoSomething() {    // missing return type
    A a;                   // make an object of type A
    a.printMe();           // call member function
}

Upvotes: 1

lindelof
lindelof

Reputation: 35240

Assuming you want to call the printMe() member function on an object of class A:

B::DoSomething() {
  A a;
  a.printMe();
}

However you also need to declare the printMe() function to be public:

class A {
public:
  void printeMe();
}

Upvotes: 1

Related Questions