Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: 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.
like image 819
ubisum Avatar asked Dec 12 '22 20:12

ubisum


1 Answers

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).

like image 156
Cubic Avatar answered Dec 20 '22 21:12

Cubic