How to apply constant reference parameter on this code? - c++

This code is passing object to a function and I want to apply constant reference parameter on this code.
class Test
{
int num;
public :
void setNum(int z)
{
num=z;
}//end mutator
int getNum()
{
return num;
}//end accessor
};//end class
void storeNumber(Test &n)
{
int a=10;
n.setNum(a);
}
void displayNumber(Test n)
{
cout<<"number="<<n.getNum()<<endl;
}
int main()
{
Test t;
t.setNum(5);
cout<<t.getNum()<<endl;
storeNumber(t);//pass by reference;
displayNumber(t); //pass by value
cout<<t.getNum();
}
This code is passing object to a function and I want to apply constant reference parameter on this code.
Any help!!

You can do for example void displayNumber(const Test &n) but then if you call methods of the Test class, they must have the const qualifier too (for example int getNum() const). If you pass Test as const & to a function, then you won't be able to use void setNum(int z) function as it violates the constantness of the class.
Edit:
Here is the full code:
class Test
{
int num;
public :
void setNum(int z)
{
num=z;
}//end mutator
int getNum() const
{
return num;
}//end accessor
};//end class
void storeNumber(Test &n)
{
int a=10;
n.setNum(a);
}
void displayNumber(const Test &n)
{
cout<<"number="<<n.getNum()<<endl;
}
int main()
{
Test t;
t.setNum(5);
cout<<t.getNum()<<endl;
storeNumber(t);//pass by reference;
displayNumber(t); //pass by value
cout<<t.getNum();
}

Related

friend function in C++ is not accessing private members

I am learning C++ and I have written the below given simple program to understand the working of friend function
(ignore all the complication I made by using complex syntax in the code because I am learning and I practice the syntax that I learn in programs).
The friend function is not accessing the private members of test and stu.
#include<iostream>
#include<conio.h>
class test;
class stu
{
private:
int z;
public:
stu(int z)
{
this->z=z;
}
friend disp(stu,test);
~stu(void)
{
std::cout<<"Destructor of stu class is executed!!"<<std::endl;
}
};
class test{
private:
int x;
public:
test(int a)
{
x=a;
}
friend disp(stu,test);
~test(void)
{
std::cout<<"Destructor is executed!!"<<std::endl;
}
};
class test2:public test
{
private:
int b;
public:
test2(int b)
{
this->b=b;
}
void show(void);
~test2(void)
{
std::cout<<"Destructor of second class executed!!"<<std::endl;
}
};
int main()
{
test t1(3);
test2 t2(5);
t2.show();
stu s1(10);
disp(s1,t1);
return 0;
}
void test2::show(void)
{
std::cout<<"Value of k = "<<b<<std::endl;
}
void disp(stu s2, test t2)
{
int sum;
sum = s2.z + t2.x;
std::cout<<"Sum = "<<sum<<std::endl;
}
Try to define the disp function before the main function :
void disp(stu s2, test t2)
{
int sum;
sum = s2.z + t2.x;
std::cout<<"Sum = "<<sum<<std::endl;
}
int main()
{
test t1(3);
test2 t2(5);
t2.show();
stu s1(10);
disp(s1,t1);
return 0;
}
and change the disp function signature as:
friend void disp(stu,test);

problem with variable inside variable reverts once changed changed

I'm having the problem where once I change a variable it seems to be unchanged when referenced later
in the code.
class foo
{
private:
string name;
public:
foo(string _name)
:name(_name)
{}
void info()
{ cout<<name; }
void newName(string new_name)
{ name = new_name; }
};
class bar
{
private:
string _name;
vector<foo> _content;
public:
foo at(int i)
{ return _content.at(i); }
void push_back(foo newFoo)
{ _content.push_back(newFoo); }
};
int main()
{
foo test("test");
bar kick;
kick.push_back(test);
kick.at(0).newName("nice");
kick.at(0).info();
return 0;
}
I would like the program to return "nice" but it returns "test".
I imagine this has something to with scope but I do not know.
How would I write something that can get around this problem?
This member function
foo at(int i)
{ return _content.at(i); }
returns a copy of the object stored in the vector.
If you want to get the expected result then return reference.
foo & at(int i)
{ return _content.at(i); }
const foo & at(int i) const
{ return _content.at(i); }

Storing functions from class in array and invoke them c++

i try store a functions(methods) from class in array and use them.
The error handle is
In function 'int main()':| 'actions' was not declared in this
scope
this my code(i delete unnecessary code)
the class.h:
class Calculator
{
public:
int num1,num2;
void (Calculator::*actions[4])();
void add();
void minuz();
void multi();
void div();
Calculator();
};
class.cpp:
void Calculator::add()
{}
void Calculator::minuz()
{}
void Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
actions[0]=add;
actions[1]=minuz;
actions[2]=div;
actions[3]=multi;
}
main:
Calculator cal;
.....
.....
cal.*actions[num]();
C++ syntax for function pointer declaration is quite complicated, so it better use typedefs
To call function by pointer you need extra () around dereferenced function pointer.
Finally it will be:
class Calculator
{
public:
typedef void (Calculator::*action)();
int num1,num2;
action actions[4];
void add();
void minuz();
void multi();
void div();
Calculator();
};
void Calculator::add()
{}
void Calculator::minuz()
{}
void Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
actions[0]=&Calculator::add;
actions[1]=&Calculator::minuz;
actions[2]=&Calculator::div;
actions[3]=&Calculator::multi;
}
int main(int, char**) {
Calculator cal;
int num = 0;
(cal.*cal.actions[num])();
return 0;
}
for better readability I'd suggest add function Calculator::call_by_index(int):
void Calculator::call_by_index(int index)
{
(this->*actions[index])();
}
and call it in such way:
cal.call_by_index(num);
Using a typedef usually helps: (c++03)
Live On Coliru
class Calculator
{
public:
int num1,num2;
typedef void (Calculator::*Action)();
Action actions[4];
Calculator() {
actions[0]=&Calculator::add;
actions[1]=&Calculator::minuz;
actions[2]=&Calculator::div;
actions[3]=&Calculator::multi;
}
private:
void add() {}
void minuz() {}
void multi() {}
void div() {}
};
int main() {
Calculator cal;
(cal.*cal.actions[1])();
}
C++11 aliases
C++11 makes it easier:
using Action = void (Calculator::*)();
Action actions[4];
See also https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types
Live On Coliru
std::function<>
Also in c++11 (or boost if you want it in c++03):
using Action = std::function<void(Calculator&)>;
Action actions[4];
Which you would still call like
cal.actions[1](cal);
I'd pre-bind to the Calculator instance:
Live On Coliru
#include <functional>
class Calculator
{
public:
int num1,num2;
using Action = std::function<void()>;
Action actions[4];
Calculator() {
actions[0] = [this]() { add(); };
actions[1] = [this]() { minuz(); };
actions[2] = [this]() { multi(); };
actions[3] = [this]() { div(); };
}
private:
void add() {}
void minuz() {}
void multi() {}
void div() {}
};
int main() {
Calculator cal;
cal.actions[1]();
}
You're not calling it right. Since actions is a member of Calculator, you need to reference a Calculator object to get at it.
(cal.*(cal.actions[num]))();
The first cal is the object you're wanting to call the action with, and the second cal is used to access the action you want to call.

How to start with Classes in c++

I at classes and objects of C++, where i am facing difficulties to understand the concept of deceleration of a class, for which i have make a little program which is not compiling, anybody will guide me?
#include <iostream>
using namespace std;
class myClass{
friend increment(myClass, int);
private:
int topSecret;
public:
myClass(){
topSecret = 100;
}
void display(){
cout<<"The value of top Secter is"<<topSecret;
}
};
void increment(myClass A, int i){
A.topSecret += i;
}
int main() {
myClass x;
x.display();
increment(x,10);
x.display();
}
Change
friend increment(myClass, int);
to
friend void increment(myClass &, int);
That should fix your compilation errors.
To modify the original object passed to a function, declare the function to take a reference:
void increment(myClass A, int i){
to
void increment(myClass &A, int i){
Arun's answer shows you how to fix your compilation error, but this is not how you should design a class. Defining non-member friend functions to access your internal data will often lead to maintenance issues and bugs. You would be better off either declaring increment as a public member function, or defining getter and setters for your class:
class myClass{
private:
int topSecret;
public:
//use initialization list instead of setting in constructor body
myClass() : topSecret(100) {}
//getter, note the const
int GetTopSecret() const { return topSecret; }
//setter, non-const
void SetTopSecret(int x) { topSecret = x; }
//member version
void increment (int i) { topSecret += i; }
};
//non-member version with setter
//note the reference param, you were missing this
void increment(myClass &A, int i){
A.SetTopSecret(A.GetTopSecret() + i);
}
Add void bebore increment in class definition as Arun A.S said.
You can't change A.topSecret in increment function because you take object by value, so you just change temporary object, use instead void increment(myClass &A, int i)

How can I make this function act like an l-value?

Why can't I use the function ColPeekHeight() as an l-value?
class View
{
public:
int ColPeekHeight(){ return _colPeekFaceUpHeight; }
void ColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
if( v.ColPeekHeight() > 0.04*_heightTable )
v.ColPeekHeight()-=peek;
}
The compiler complains at v.ColPeekHeight()-=peek. How can I make ColPeekHeight() an l-value?
Return the member variable by reference:
int& ColPeekHeight(){ return _colPeekFaceUpHeight; }
To make your class a good one, define a const version of the function:
const int& ColPeekHeight() const { return _colPeekFaceUpHeight; }
when I declare the function with the
two consts
When you want to pass an object into a function that you don't expect it to modify your object. Take this example:
struct myclass
{
int x;
int& return_x() { return x; }
const int& return_x() const { return x; }
};
void fun(const myclass& obj);
int main()
{
myclass o;
o.return_x() = 5;
fun(o);
}
void fun(const myclass& obj)
{
obj.return_x() = 5; // compile-error, a const object can't be modified
std::cout << obj.return_x(); // OK, No one is trying to modify obj
}
If you pass your objects to functions, then you might not want to change them actually all the time. So, to guard your self against this kind of change, you declare const version of your member functions. It doesn't have to be that every member function has two versions! It depends on the function it self, is it modifying function by nature :)
The first const says that the returned value is constant. The second const says that the member function return_x doesn't change the object(read only).
It can be rewritten like:
class View
{
public:
int GetColPeekHeight() const { return _colPeekFaceUpHeight; }
void SetColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
cph = v.GetColPeekHeight();
if ( cph > 0.04 * _heightTable )
v.SetColPeekHeight( cph - peek );
}