Reputation: 513
I am new to C++, and confused about how does a class access a public method in another class in C++. For example,
//.h of class A
class A {
public:
void setDimension (int width, int height);
A* obj;
}
//.cpp of class A
#include "A.h"
void A::setDimension (int width, int height) {
// do some stuffs here
}
//.h of class B
#include "A.h"
class B {
public:
void function ();
//do something here
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
obj->setDimension(int width, int height);
}
And now I want the class B can access the public method "setDimension" in class A. I think the dependency files are included, but when I run the program, I got an error says that setDimension was not declared in this scope
. How can I call the setDimension method inside class B. Many thanks!
Upvotes: 1
Views: 10895
Reputation: 83
You have first to create an instance of object A and then call setDimension on this instance.
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
A myInstance;
myInstance.setDimension(10, 10);
}
Or you need to declare the method as static and can call it without instantiation:
//.h of class A
class A {
public:
static void setDimension (int width, int height);
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
A::setDimension(10, 10);
}
If Class A is abstract:
//.h of class B
#include "A.h"
class B : A {
public:
void function ();
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
this->setDimension(10, 10);
}
Upvotes: 5
Reputation: 93
You can declare the method setDimension(int width,int height);
in class A as static.
static void setDimension(int width,int height);
void B::function(){
A::setDimension()
}
You access static member functions using the class name and the scope resolution operator ::
Upvotes: 0
Reputation: 9988
You need to create an A
(and choose a particular width and height, or pass those in from somewhere) so that you can use its method
void B::function() {
A mya;
int mywidth = 10;
int myheight = 20;
mya.setDimension(mywidth, myheight);
}
Upvotes: 0