Calling a function from one class in another class - c++

If I have these two sets of .cpp and .h files set up like this and I l want to put an add() function in a.cpp that adds ten integers and returns sum. Then I have class b that will return the average but I want to use the sum of the ten integers that I got from class a. How can I call function add() in function average() so it can return the sum? I don't know if this is getting my question across well, I just made this example up to try it illustrate it.
class a {
private:
int a[10];
public:
a( );
int add( int);
};
class b {
private:
int d;
public:
int average(int );
}

You can call member functions on an object of a class, not on the class itself. Creating an object is almost as creating a variable, for example a my_a;. Then you can use the add member function of the my_a object as my_a.add(42).
If you do not need objects (but do need classes for some reason), use static member functions and variables as follows.
class MyClass {
private:
static int variable;
public:
static int accessor() { return variable; }
};
In this case, you can call the static member function without creating an instance as MyClass::accessor().

class A {
public:
static int add(int);
};
class B {
public:
void average(int val){
A::add(val);
// Some logic
}
};

Related

Dont allow access to member variable directly within same class

I am not sure is my question is right or not? But let me still try to ask once.
I have a Class with have few member variables defined. As per OO concepts, every member function can access , all member variables of its class.
But I want these member variable to be accessed via specific methods (Lets say Getters) , even within same class member functions.
It there any way to do it?
class A {
public:
void func1();
void func2();
B getB();
private:
B b;
}
void A::func1() {
b.functionFromB(); // function uses member variable b directly
}
void A::func2() {
B b1=getB(); // function ask for B from a function and then uses it. // I need something like this... And ensure each function uses same way otherwise there should be warning...
b1.functionFromB();
}
Thanks,
Kailas
No, there is not. You can do it via encapsulation and inheritance like:
class shape
{
private:
int angles;
protected:
shape(int angles_):angles(angles_){};
int getAngles() const;
}
class square : private shape
{
public:
square():shape(4){}
void doSth()
{
\\ you can access angles only via getAngles();
}
}
Any private members of the class can be accessed from within the class, but not by users of the class. So it looks like you need private members and public methods that allow access to them.
class A
{
private:
int a;
public:
int getA() {return a;}
};
int main()
{
A inst;
int t;
inst.a =5; // error member a is private
t = inst.getA(); //OK
}
The concept extends fine to nested class declarations in case you only want to allow instance of a class to be created from another class; details here
As others have said - you have to add an additional layer.
If you want to give access to specific methods then you can use the friend keyword. E.g.
// Public.h
#pragma once
class Public
{
public:
Public();
int GetI() const;
float GetF() const;
private:
std::unique_ptr<Private> p_;
};
//Public.cpp
#include "Public.h"
Public::Public()
: p_(new Private)
{
}
int Public::GetI() const
{
return p_->i_;
}
float Public::GetF() const
{
return p_->f_;
}
// Private.h
#pragma once
class Private
{
friend int Public::GetI() const;
friend float Public::GetF() const;
int i_;
float f_;
};
Keep in mind that every friend method can access ALL private members.
If you really really want to limit which methods can access which members then you can wrap each member in a separate class/struct and make only the getter/setter of that member a friend of that class/struct but I would not recommend this approach.

C++ declaring a static object in a class

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
What I want to achieve is to get int x in B::start() to equal int x in class A (4).
I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?
If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.
Error
error LNK2001: unresolved external symbol "private: static class A B::obj1"
Thanks!
You should initialize static var, the code:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
A B::obj1; // init static var
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
As thinkerou said, you need to include the declaration of the variable:
A B::obj1;
For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.
C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

Accessing private variables through levels of classes.

So in my current understanding of how to use encapsulation correctly it is a good rule of thumb to make variables private and access them through member functions of the class like this:
class Aclass{
private:
int avar;
public:
void ch_avar(int val){avar = val};
int get_avar() {return avar;}
};
My question is how would I access a private member of a class instance which is its self a private member of another class. Here is an example of the way I have been trying to do it (not retyping the example above for brevity)
class LargerClass{
private:
int other_var;
Aclass A; //has two instances of class "Aclass"
Aclass B;
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int get_avar(Aclass X){return X.get_avar();}
};
Now In my real program there are a few more levels of this and I keep getting the compilation error that "Aclass" is an unknown type. Even though I have included the header file for Aclass in the Larger class. Since I am stuck I thought It would be good to find out if this is even the correct (or an acceptable way) of doing what I want. I am new to OOP and this feels sloppy to me.
To access the private member of a class instance which is its self a private member of another class, can be done this way. You don't need to pass a Aclass X. It is unneccessary. You can call it by the instance name you have given..
class LargerClass{
private:
int other_var;
Aclass A; //has two instances of class "Aclass"
Aclass B;
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int get_avar_A(){return A.get_avar();}
};
If you have 20 instances of Aclass, rather you create a vector of Aclass instances.
class LargerClass{
private:
int other_var;
Aclass A[20];
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int[] get_avar_A()
{
int other_var[20];
for(int i= 0; i<20; i++)
{
other_var[i] = A[i].get_avar();
}
return other_var;
}
};

c++ Creating vector of function pointers in a given class, with function being a member of a different class

I am having a vector of function pointers in one class and to it i want to pass address of function in some other class. The following implementation gives errors. What is the correct way?
class A
{
public:
void func ()
{
}
};
class B
{
public:
std::vector<void(*)()) myVec;
void update_func()
{
myVec.push_back(&A::func);
}
};
int main()
{
B* b = new B;
b->update_func();
return 0;
}
A pointer to the non-static member function A::func doesn't have type void(*)(void), it has type void(A::*)(void). So either change the vector to match the elements that you want it to have, or else use a pointer to a function of the correct type for the vector.
A's func() has to be static to match the declaration of the function pointer. Meanwhile, it needs to be public such that it is accessible to class B.
update_func() in B also needs to be public since otherwise in main it is not accessible.
vector declaration has typo, it has to be vector<>, not vector<).
//
class A
{
public:
static void func ()
{
}
};
class B
{
std::vector<void(*)()> myVec;
public void update_func()
{
myVec.push_back(&A::func);
}
};
int main()
{
B* b = new B;
b->update_func();
return 0;
}
This code has many issues..
first b->func should have () after it if you want to call that function..
second.. what is void update func().. also bad code..
third you cannot use these functions since they are private...
you do however push it correctly into the vector...

How access class variables in c++

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable.
I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
static is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
You made the class variable protected or private, thus rendering it inaccessible from other code.
You forgot to specify the full scope of the class variable (with A:: in this example).
I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.
yes you can bro, try this
struct car{
string model;
string paint;
int price;
};
int main(){
// creates an object of the class car
car BMW;
// assign the values
bmw.model = "m sports";
bmw.paint ="red";
bmw.price = 24000;
}