Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8397107
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T20:42:24+00:00 2026-06-09T20:42:24+00:00

I have some code where I have a pointer to an object. I call

  • 0

I have some code where I have a pointer to an object. I call a method on that pointer but the behaviour of the method is wrong in this case. I tried calling a method on the object itself and this actually gives the desired behaviour of the method.

Why does this cause different behaviour?

Also is there a way of assigning an object to a new variable without using pointers because I want the behaviour for the method called on the object itself?

Thanks.

EDIT:

Hopefully a sufficient example:

In a Robot class:

std::vector<ProjectOne::R_ID> Robot::positions;
int Robot::ID = -1;

Robot::Robot(double x, double y)
{
    ++ID;
    robot_ID = ID;
    initialX = x;
    initialY = y;
    // Placeholder. Doesn't actually get used properly atm.
    fWidth = 0.35;
    px = x;
    py = y;

    ProjectOne::R_ID msg;   
    msg.R_ID = robot_ID;
    msg.x = x;
    msg.y = y;
    positions.push_back(msg);

    string robotOdom = "robot_" + int2str(robot_ID) + "/odom";
    string robotVel = "robot_" + int2str(robot_ID) + "/cmd_vel";

    RobotOdometry_sub = n.subscribe<nav_msgs::Odometry>(robotOdom,1000,&Robot::ReceiveOdometry,this);
    RobotVelocity_pub = n.advertise<geometry_msgs::Twist>(robotVel,1000);
    ros::spinOnce();
}

void Robot::ReceiveOdometry(nav_msgs::Odometry msg)
{
    //This is the call back function to process odometry messages coming from Stage.    
    px = initialX + msg.pose.pose.position.x;
    py = initialY + msg.pose.pose.position.y;
    ptheta = angles::normalize_angle_positive(asin(msg.pose.pose.orientation.z) * 2);
}

int Robot::selectLeader()
{
    int leader_ID = robot_ID;
    double lowestDistance = 9999999999.9;
    for (unsigned int i=0;i<positions.size();i++)
    {
        double distance = calculateDistance(positions[i].x, positions[i].y, 0.0, 0.0);            
        if (distance < lowestDistance && distance != 0.0)
        {
            leader_ID = positions[i].R_ID;
            lowestDistance = distance;
        }
    }
    ROS_INFO("leader is: %d", leader_ID);
    return leader_ID;
}

double Robot::calculateDistance(double x1, double y1, double x2, double y2)
{
    double deltax = x2 - x1;
    double deltay = y2 - y1;
    double distanceBetween2 = pow(deltax, 2) + pow(deltay, 2);
    double distanceBetween = sqrt(distanceBetween2);
    return distanceBetween;
}

double Robot::calculateHeadingChange(double x, double y)
{
    double deltax = x - px;
    double deltay = y - py;
    double angleBetween = atan2(deltay, deltax);
    double headingChange = angleBetween - ptheta;
    return headingChange;
}

void Robot::align(double x, double y)
{
    ros::Rate loop_rate(10);
    double headingChange = calculateHeadingChange(x, y);
    double angularv = headingChange / 5;
    double heading = ptheta + headingChange;

    while (heading > 2 * M_PI)
    {
        heading -= 2 * M_PI;
    }
    while (heading < 0)
    {
        heading += 2 * M_PI;
    }
    geometry_msgs::Twist msg;
    msg.linear.x = 0;
    msg.angular.z = angularv;
    while (ros::ok())
    {
        RobotVelocity_pub.publish(msg);
    ros::spinOnce();
    ROS_INFO("Heading Change %f pthea is %f %f %f", headingChange, ptheta, px, py);
    loop_rate.sleep();
    }
}

And this is the code that calls the method:

int main(int argc, char **argv) {
        ros::init(argc, argv, "robotNode");

    Robot r1(5,10);
    Robot r2(15,20);
    Robot r3(10,30);
    Robot r4(25,16);
    Robot r5(5,28);
    Robot r6(10,10);

    Robot Group[6] = {r1, r2, r3, r4 ,r5, r6};
    std::vector<Robot> Herd;
    int leaderID = r1.selectLeader();

    Robot * leader;

    for (int i=0;i<6;i++) {
        if (Group[i].robot_ID  == leaderID) {
            leader = &Group[i];
        } else {
            Herd.push_back(Group[i]);
        }
    }

    (*leader).align(0.0, 0.0); //Problem area
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T20:42:26+00:00Added an answer on June 9, 2026 at 8:42 pm

    The problem is that your array (Group) and vector (Herd) both contain copies of the automatic objects (r1 and friends); so anything you do to those will not affect the originals.

    You probably want to work with pointers instead:

    Robot * Group[6] = {&r1, &r2, &r3, &r4, &r5, &r6};
    std::vector<Robot*> Herd;
    

    In general, you need to be careful not to dereference these pointers after the objects are destroyed; in this case you’re fine, since the lifetimes of the array and vector are contained within those of the objects.

    It might make sense to make the Robot class uncopyable, to prevent this kind of mistake.
    In C++11, you do this by deleting the copy constructor and copy assignment:

    Robot(Robot const &) = delete;
    void operator=(Robot const &) = delete;
    

    In older language versions, declare them private, with no implementation; or (better still) derive from a base class that does that.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an object that uses some underlying native resources, and has a pointer
I have some code that will change the background color of a specific label
I have some code here that uses bitsets to store many 1 bit values
I have some code that is supposed to return an NSString. Instead it is
I have some code that generates Visio masters for me, and some masters have
I have some code that causes the box2d physics simulation to stutter forever after
I have some code that runs a model in a loop. Each iteration of
I have some code that shows results in a table Right now it will
So I have this huge tree that is basically a big switch/case with string
I have some .NET remoting code where a factory method, implemented in some server

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.