0

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

1
  • Show your real code as fed to the compiler, and any error messages you've got. Commented Dec 2, 2013 at 12:22

2 Answers 2

1

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(); } 
Sign up to request clarification or add additional context in comments.

4 Comments

Error: 'A' was not declared in this scope
@UmeshMoghariya: You'll need the definition of class A before you can create an object or call a member function. If it's in a header file, then include that. If you're just writing a single source file, then make sure A comes before B. This should all be covered by your introductory book.
@MikeSeymour yes, I am using a header file and included it in the code.
I had error due to a different Bug, but the solution holds correct.
1

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.