friend function c++ inside class - c++

i wrote this code but friend function is not working(foodmoney and hobbymoney are not declare in my friend function. where is my Error here ?
#include <iostream>
using namespace std;
class myBase
{
private:
int friendvar;
int foodmoney;
int hobbymoney;
public:
void setdata();
myBase(){friendvar=0;}
friend void caldata(myBase &mbo);
};
void myBase::setdata()
{
cout<<"Enter foodmoney :" ;cin>>foodmoney;
cout<<"enter hoobymoney:";cin>>hobbymoney;
}
void caldata(myBase &mbo)
{
mbo.friendvar=(foodmoney+hobbymoney)/2;
cout<<mbo.friendvar<<endl;
}
int main()
{
myBase baseobj;
baseobj.setdata();
myBase friends;
caldata(friends);
return 0;
}

mbo.friendvar=(foodmoney+hobbymoney);
should be
mbo.friendvar=(mbo.foodmoney+mbo.hobbymoney);
etc. etc.
Friend functions are not member functions, so they do not have special access to any particular object. You must specify which object you wish to access (by using mbo in your case).
Having said that I can't see any good reason why caldata is a friend function. Why not make it a regular member function? Or maybe you should make it a friend function with two arguments? It's hard to say what you're trying to achieve here.

change
cin>>foodmoney;
to
cin>>mbo.foodmoney;
and change
cin>>hobbymoney;
to
cin>>mbo.hobbymoney;

Your code doesn't compile at all. Fix is described already. But to make ti complete:
As you have referenced friendvar using mbo.friendvar, do the same for foodmoney and hobbymoney.
Also you have not initialized foodmoney and hobbymoney in your constructor. And in your call to caldata(friends); you are therefor getting random result printed on screen.
Last: you instantiate new object with myBase friends; so this is completely new object that is not affected by previous call of setdata().
Your low level requirements for this function are not defined in your question, I cannot help more.

Related

I can't create public inherited class - Something is wrong with constructors C++

Hey there fellow programmers, I'm having a big issue with this thing! I just want to create a class that inherits stuff from previous class, but the problem is that in both class I have constructors and the compiler just won't compile this simple code - It's telling me - 10.12.2012.3.cpp:28:3: error: no matching function for call to ‘Monitor::Monitor()’: Please Ignore the main fuction - It's not doing anything in particular, sine I can't get past this problem :/ Sorry for dumb question, but I couldn't find the specific answer PS: my first post here :)
#include <iostream>
#include <string.h>
using namespace std;
class Monitor
{
protected:
int sifra;
public:
Monitor (int sifra1)
{
sifra = sifra1;
}
};
class Prodaja : public Monitor
{
protected:
int monster;
public:
Prodaja (int monster1)
{
monster = monster1;
}
};
int main()
{
int sifra1;
string firma1, model1, dobavitelj1;
float nabava1, cena1;
return 0;
}
Monitor does not have a default constructor.
You have to invoke its constructor in the constructor of the derived class. That's because otherwise the Prodaja instance doesn't know how to construct its Monitor part.
So you need
Prodaja (int monster1): Monitor(monster1)
or to define a constructor of Monitor that takes no parameters (or has a default parameter).

c++ use default functions in class with same name

What would be a good approach to implement a class in c++ like this:
Someclass.h:
class SomeClass
{
public:
SomeClass();
void kill();
}
Someclass.cpp:
SomeClass::kill(){
kill();//This would cause an infinit recursion
//How to fix it?
}
So what I'm trying to do is redeclare a function within my object as a method.
I can't find if there is a namespace or something simular, that contains "kill()", "sleep(int sec)".
Hope you can help.
SomeClass::kill(){
::kill();
}
:: accesses global scope

Implementing a template class interface

I am relatively new to c++ and am having a heck of a time getting my main program to instantiate my class. I am used to java so I'm not sure if I am mixing up the two languages as I attempt to do this and that is my problem or maybe I just don't understand the concept correctly.
The object of my program: The object of this program is to create a template class from an interface that will make a sorted array that you can add and remove items from it while keeping it sorted.
Note: Please help me actually understand this process as to just telling me the exact code to use because I really want to understand what I am doing wrong for next time.
Step 1: I created my sorted interface:
sortedInterface.h
#ifndef _SORTED_INTERFACE
#define _SORTED_INTERFACE
#include <vector>
using namespace std;
template<class ListItemType>
class sortedInterface
{
public:
virtual bool sortedIsEmpty();
virtual int sortedGetLength();
virtual bool sortedInsert(ListItemType newItem);
virtual bool sortedRemove(ListItemType anItem);
virtual bool sortedRetrieve(int index, ListItemType dataItem);
virtual int locatePosition(ListItemType anItem);
}; // end SortedInterface
#endif
then I used the interface to create the sorted.h file:
sorted.h
#include "sortedInterface.h"
#include <iostream>
#ifndef SORTED_H
#define SORTED_H
using namespace std;
template<class ListItemType>
class sorted
{
public:
sorted();
sorted(int i);
bool sortedIsEmpty();
int sortedGetLength();
bool sortedInsert(ListItemType newItem);
bool sortedRemove(ListItemType anItem);
bool sortedRetrieve(int index, ListItemType dataItem);
int locatePosition(ListItemType anItem);
protected:
private:
const int DEFAULT_BAG_SIZE = 10;
ListItemType items[];
int itemCount;
int maxItems;
};
#endif // SORTED_H
and finally I created the sorted.cpp (I only included the constructor for now as I can't even get that working)
#include "sorted.h"
#include <iostream>
using namespace std;
template<class ListItemType>
sorted<ListItemType>::sorted()
{
itemCount = 0;
items[DEFAULT_BAG_SIZE];
maxItems = DEFAULT_BAG_SIZE;
}
My main program:
#include "sortedInterface.h"
#include "sorted.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
sorted<string> sorted1 = new sorted();
return 0;
};
Any help is appreciated in explaining where my logic is failing on this and any hints on how to properly execute my task. Thanks!
1) operator "new" returns a pointer, not an object.
sorted<string>* sorted1 = new sorted<string>();
2) However, in your small example, there is no need to create sorted1 using "new".
sorted<string> sorted1;
One word of advice -- Java is not C++. You made the two mistakes that many first-time Java programmers make when writing C++ code, namely 1) believing that to create an object, you must use "new", and 2), that "new" returns a reference.
There are a few things wrong with your interface/implementation. A class template is usually implemented entirely in the header in which it's declared; this is because the compiler creates a whole new type for each type you use with your template.
Second, in your sortedInterface template, you've made the members virtual which still requires a definition, but you do not supply one. You can mark your member functions with = 0; to make them all pure virtual, which means the classes that inherit your sortedInterface will have to implement those members instead.
Third, as PaulMcKenzie pointed out, operator new() returns a pointer to a heap-allocated object, but you're expecting a value type.
Finally, please take a look at smart pointers if you're using naked new()s everywhere.
I notice the following additional anomalies in the entire implementation:
An interface is something which should be non-instantiable but it is
instantiable in your case (because there is not even a single pure
virtual function in your so called interface) Standard rule is to
make all the functions in the interface pure virtual (=0)
class Sorted does not inherit from the so-called interface
sortedInterface
You have not defined all versions of your constructor in your class
Sorted
If you want the polymorphism to work (Interface to Concrete), you
need to have virtual class destructors in both the interface and
concrete class

Accessing private fields and function from main

I've programmed only in Java in my career and started using C++ since 10 days, so this question may seem strange to many of you.
I have defined the structure of a class in a header file:
#include "ros/ros.h"
#include "nav_msgs/Odometry.h"
#include "geometry_msgs/Pose.h"
#include "geometry_msgs/Point.h"
#include "stdio.h"
#include "sensor_msgs/LaserScan.h"
#include "list"
#include "vector"
#include "scan_node.h"
#include "odom_node.h"
#include "coord.h"
class stage_listener{
public:
stage_listener();
private:
std::list<odom_node> odom_list;
std::list<scan_node> scan_list;
std::list<coord> corners_list;
std::list<coord> polar2cart(std::vector<float>, float, float, float, float);
void addOdomNode (const nav_msgs::Odometry);
void addScanNode (const sensor_msgs::LaserScan);
void extractCorners(std::vector<float>, float, float, float, float);
int distance (float, float, float, float, float);
void nodes2text(std::vector<odom_node>, std::vector<scan_node>);
int numOdom();
int numScan();
};
In the associated .cpp file, I wrote a main:
int main(int argc, char **argv){
char buffer [1024];
while(1){
int i = fscanf(stdin,"%s",buffer);
if(strcmp("exit",buffer) == 0)
exit(0);
else if(strcmp("num_nodes",buffer) == 0){
ROS_INFO("Odometry nodes: %i\nScan nodes: %i",numOdom(),numScan());
}
else{}
}
}
The ROS_INFO function is part of Willow Garage's ROS and you can intend it like a normal printf, taking exactly arguments in the same form.
On compiling code, I get the following:
/home/ubisum/fuerte_workspace/beginner/src/stage_listener.cpp: In function ‘int main(int, char**)’:
/home/ubisum/fuerte_workspace/beginner/src/stage_listener.cpp:223:5: error: ‘numOdom’ was not declared in this scope
/home/ubisum/fuerte_workspace/beginner/src/stage_listener.cpp:223:5: error: ‘numScan’ was not declared in this scope
Do you know the cause of the errors? In Java, you can access private fields/functions, so I can't understand the reason why in C++ it's not possible.
In Java, you can access private fields/functions
No you can't, unless you're using reflection. That's the entire point of making something private. I think you're mixing up public and private here. (You can access private static fields and methods in java from the classes own main method though). The main function in C++ is not associated with a class (and even if it were, your code still wouldn't work because you're attempting to access instance members statically).
There are a few things here.
Firstly, you need to make stage_listener object to call its methods or make methods static then use scope resolution operator to call the functions if you want objects to share same method.
Secondly, you cannot access private variables( that is the point of data hiding in OO languages.)
So, you need to make functions public in the class and either create object of the class or make functions static and call them using scope resolution operator. Depends totally on what are you trying to accomplish. I hope this helps.
Usually, in C++, we use the functions as a public.
You did it as private, so just in the scope of own class you'll can access them. So, if yoy're trying to use them in the main, we can think that these functions should be public.
And you need to declare an object of the class. So you'll can access the function using object.function(); command.
1) You can't call methods without instantiating the class, or simply put you have to create object first.
2) Even if you create an object of your class your object can't call private methods. So make numOdom and numScan public methods.
You can't access any private method outside of on of this class's method (even in Java).
Set the methods you want to use outside as public
In C++, the main function is not part of the class you defined (even though it's "in the associated .cpp file"), so it can't access private fields. In C++ as in Java, only functions that are declared in the class are part of the class, and so can access private fields.
1) Public methods in the public section
2) To call the non-static public methods of the class, first create an instance of the class
class stage_listener{
public:
stage_listener()
{
}
//all methods are not implemented
void addOdomNode (const nav_msgs::Odometry) {}
void addScanNode (const sensor_msgs::LaserScan) {}
int numOdom() { return 0; }
int numScan() { return 0; }
private:
std::list<float> odom_list;
........
std::list<float> polar2cart(std::vector<float>, float, float, float, float)
{
//empty list
return std::list<float>();
}
........
};
int main(int argc, char **argv){
char buffer [1024];
while(1){
int i = fscanf(stdin,"%s",buffer);
if(strcmp("exit",buffer) == 0)
exit(0);
else if(strcmp("num_nodes",buffer) == 0){
//create object on the stack
stage_listener sl;
ROS_INFO("Odometry nodes: %i\n
Scan nodes: %i\n",
sl.numOdom(),
sl.numScan());
}
else{
return 1;
}
}
return 0;
}

C++ making a class function member of another class function

I sincerely hope that people on here don't mind these sorts of questions.
After having searched plenty of times, perhaps with the wrong search terms - nevertheless - I do not seem to be able to find ANYTHING on this.
Yes, I have looked through cplusplus' documentation, yet I still could not find out the answer.
My question is simple, how do I make it so that a function can only be called via another function?
Here's an example
class someclas{
public:
void screen():
void setsomevariable (int somevariable){}
}clas;
And when I call the function, setsomevariable(), it should only be able to be used after having called the screen function. As such:
clas.screen().setsomevariable(..);
Again, how do I make this function a member of screen() alone?
This does match your requirements, but doesn't necessarily meet your needs. Would like to help more but you're stubbornly refusing to give details...
class Screen {
public:
void setsomevariable (int somevariable) {}
};
class someclas {
Screen s;
public:
Screen& screen() { return s; }
} clas;
A member function belongs to a class. You can't make a function a member of another.
You could keep a boolean in your class, and throw an exception if screen wasnt called before. But it's an ugly solution..
class someclas{
public:
someclas & screen() { // returns a reference to your class to enable the clas.screen().setsomevariable() syntax
screenCalled = true;
return *this;
}
void setsomevariable (int somevariable){
if (!screenCalled) {
throw std::exception();
}
// some code
screenCalled = false;
}
bool screenCalled;
}clas;