How to create instance of a class globally

Hi guys,

I have a class named Robot.cpp and another voInterpreterClient.cpp. I need to create instance of voInterpreterClient.cpp in Robot.cpp globally. voInterpreterClient.cpp contains a constructor

voInterpreterClient::voInterpreterClient(Connection_Info conn,int number)

Now, I need to create an instance for this class globally.. Please, tell me how should I create an instance in Robot.cpp.

voInterpreterClient client(conn,1024); // This is how we create an instance. But I believe i can't do this globally.

Please, help me.

Thank you so much.
What do you mean by "globally"? Do you mean one instance for every Robot object? If that's the case you can use a static voInterpreterClient in your Robot class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// robot.h

class Robot
{
// ...
protected:
  static voInterpreterClient theClient;
};

// robot.cpp

#include "robot.h"

voInterpreterClient Robot::theClient( /*whatever */ );


But I'm not sure this is what you're talking about. Can you clarify?
Hi Disch,

Thank you for your reply. Here, is what exactly I mean.

I have Robot.cpp and voInterpreterClient.cpp in a folder. The voInterpreterClient.cpp has a constructor

voInterpreterClient::voInterpreterClient(Connection_Info connIn, int maxInputBufferSize)

I need to create an instance of this in Robot.cpp. In Robot.cpp I have two function

void Robot::setupConnection();
void Robot::transmitData();

I am creating instance of voInterpreterClient in void Robot::setupConnection() as
voInterpreterClient client(conn, 1024);

Everything, is fine till here. But, I need to access the client object in void Robot::transmitData(). For that I need to declare voInterpreterClient client object as a global one. Here, are the functions
void Robot::setupConnection()
{
//Declare the connection object
Connection_Info conn;

// Reading IP address and port no. from a configuration file
ifstream _config;
string _ipaddr,_hostInfo[2];

_config.open("configuration.txt");

int i=0;
while(getline(_config,_ipaddr,':'))
{
_hostInfo[i]=_ipaddr;
i++;
}

conn.host = _hostInfo[0];
conn.port = _hostInfo[1];

ofstream _configLog;
_configLog.open("configuration_log.txt");
_configLog << "// This is the IP address and port number used by the Humanoid robot to connect to Inpterpreter server" << "\n" << endl;
_configLog << "IP Address : " << conn.host << endl << "Port : " << conn.port << endl;

// Instantiate the new Client:
voInterpreterClient client(conn, 1024);

if(!client.voConnect())
{
robot_console_printf("Could not establish connection with the server\n");
exit(0);
}
else
{
robot_console_printf("Connection established\n");
}
}

void Robot::transmitData()
{
int count=0;

string srvInput="",srvOutput="";

ostringstream _output;

// for non-blocking polling:
// Receiving input from the server
if(Robot::client.poll())
{
srvInput = Robot::client.getString();
if(srvInput=="q")
{
client.voDisconnect();
robot_console_printf("Connection terminated\n");
exit(0);
}
count++;
}

key=(int)srvInput[0];
robot_console_printf("ASCII value = %d\n",key);

// Posting reply to the server
if(!srvInput.empty() && count==1)
{
_output << key;
srvOutput=_output.str();
Robot::client.publish(srvOutput);
_output.str("");
count--;
}
}

Please, help me. When I did what you told me I get errors saying that

Robot.o: In function `Robot::transmitData()':
Robot.cpp:(.text+0x5d2): undefined reference to `Robot::client'
Robot.cpp:(.text+0x5ea): undefined reference to `Robot::client'
Robot.cpp:(.text+0x666): undefined reference to `Robot::client'
Robot.cpp:(.text+0x7e1): undefined reference to `Robot::client'

Thank you
Put your code in code tags ( the # button to the right of the textbox when you're writing your post)
Can you also post your headers for Robot and voInterpreterClient?
Hi JRaskell,

Here is my code.



void Robot::setupConnection()
{
//Declare the connection object
Connection_Info conn;

// Reading IP address and port no. from a configuration file
ifstream _config;
string _ipaddr,_hostInfo[2];

_config.open("configuration.txt");

int i=0;
while(getline(_config,_ipaddr,':'))
{
_hostInfo[i]=_ipaddr;
i++;
}

conn.host = _hostInfo[0];
conn.port = _hostInfo[1];

ofstream _configLog;
_configLog.open("configuration_log.txt");
_configLog << "// This is the IP address and port number used by the Humanoid robot to connect to Inpterpreter server" << "\n" << endl;
_configLog << "IP Address : " << conn.host << endl << "Port : " << conn.port << endl;

// Instantiate the new Client:
voInterpreterClient client(conn, 1024);

if(!client.voConnect())
{
robot_console_printf("Could not establish connection with the server\n");
exit(0);
}
else
{
robot_console_printf("Connection established\n");
}
}

void Robot::transmitData()
{
int count=0;

string srvInput="",srvOutput="";

ostringstream _output;

// for non-blocking polling:
// Receiving input from the server
if(Robot::client.poll())
{
srvInput = Robot::client.getString();
if(srvInput=="q")
{
client.voDisconnect();
robot_console_printf("Connection terminated\n");
exit(0);
}
count++;
}

key=(int)srvInput[0];
robot_console_printf("ASCII value = %d\n",key);

// Posting reply to the server
if(!srvInput.empty() && count==1)
{
_output << key;
srvOutput=_output.str();
Robot::client.publish(srvOutput);
_output.str("");
count--;
}
}



Here are the header files for Robot.cpp



#include "Robot.h"

#include <device/robot.h>
#include <device/differential_wheels.h>
#include <device/servo.h>
#include <device/camera.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>
#include <sstream>
#include <fstream>



Here are the headers for voInterperterClient.cpp

#include "voInterpreterClient.h"
#include <device/robot.h>





voInterpreterClient.h

/*
* voInterpreterClient.h
*
* Created on: Feb 15, 2009
* Author: thibec
*/

#ifndef VOINTERPRETERCLIENT_H_
#define VOINTERPRETERCLIENT_H_

#include "include.h"

class voInterpreterClient {

public:
voInterpreterClient(Connection_Info, int);
~voInterpreterClient();
bool voConnect();
bool voDisconnect();
bool poll();
bool bpoll();
bool publish(std::string);
bool publish(char*, int, int);
size_t getData(char*, int);
std::string getString();
private:
// Private Functions
void bail(const char *on_what);
bool establishConnection();
bool getTransmitStream();
bool getReceiveStream();
// Private Variables
struct sockaddr_in _adr_srvr;
int _s;
int _s2;
FILE *_rx;
FILE *_tx;
char* _buffer;
int _maxInputBufferSize;
Connection_Info _connInfo;
};

#endif /* VOINTERPRETERCLIENT_H_ */


Robot.h


#ifndef Robot_H
#define Robot_H

#include <device/robot.h>

#include "voInterpreterClient.h"

// number of DOFs of the robot
#define MAX_SERVOS 63

#define SIMULATION_STEP_DURATION 16

#define STEP_NBR 180

#define STR_BUFFER_SIZE 512

class Robot {
public:
// constructor: create robot according to specification
Robot();

// destructor
virtual ~Robot() {};

void enableServoPosition(int servoId);
void setServoPosition(int servoId, float value);
float getServoPosition(int servoId);

void save_pose();
void load_pose(int id);
void create_pose();

void run();
void wait(float x);
//void play();

// Edited by Sridhar
void setupConnection();
void transmitData();
void servo_positive(int,double);
void servo_negative(int,double);
void save_image();
void process_image();

void find_ball();

void turn_right_90();
void turn_left_90();
void turn_clockwise_180();
void backward_linear_motion();
void forward_linear_motion();
void move_forward_turn_right();
void move_forward_turn_left();
void square_motion();
// Edited by Sridhar

static const char * SERVO_NAMES[MAX_SERVOS+1];
static const float SERVO_LIMITS[MAX_SERVOS][2];

private:
float _mouthPos;
float _controlStep; // simulation step size in milliseconds
DeviceTag servos[MAX_SERVOS];

int pose_file_id, save_file_id, current_servo;
int counter,key;

const unsigned char *image;

protected:
static voInterpreterClient client;

};

#endif



Please help me solve this problem.

Thank you.
Please do as JRaskell has asked and surround the posted code with code tags using the '#' button. You'll see this button to the right of your editor window.
1
2
3
4
5
6
7
8
9
10
void Robot::setupConnection()
{

   // This is not a global instance.  It is an instance created on the stack and will
   //  be destroyed the moment that setupConnection returns.

   // Instantiate the new Client:
   voInterpreterClient client(conn, 1024);

}


I see that you created the static instance within the header of the robot class. However, you did not initialize it in the .cpp file so you will get errors. Also if you create a static instance within the class, the object isn't global. It only exists for each Robot instance. Lastly, get rid of the instance that you are creating in the setupConnection function.

In Robot.cpp you need
voInterpreterClient Robot::client;

Moreover, you will need to add a default constructor to be able to construct the static instance of voInterpreterClient. The current constructor requires the connection info which isn't available at compile time. You'll need a separate member function to pass in the connection info later on.

Will there be many Robot instances? Should each robot have its own instance of voInterpreterClient? If so, then the static instance you have won't work anyway. There aren't enough details on your problem for me to help. I can only give you some possibilities and hints. If you only need the robot member functions to each access the same instance you could just have a non-static member of type voInterpreterClient so that each Robot has its own.
Last edited on
Topic archived. No new replies allowed.