1

I am trying to get the hang of C++ pointers and objects, through a small project implementing a simple Vehicle Routing Problem. Even though my code is currently working, I can't shake the feeling that my approach is completely wrong. What bugs me, are snippets of code such as :

std::map<const Route*, double>::iterator it = quantities.begin();
if ((*(*(it->first)).getDestination()).getDemand() > (*(*(it->first)).getDeparture()).getSupply())

The pointer hell situation in the if condition is the result of the get methods returning pointers to already created objects. The methods being called are :

const Departure* Route::getDeparture() const {
    return departure;
};

const Destination* Route::getDestination() const {
    return destination;
};

and

int Destination::getDemand() const {
    return demand;
};

int Departure::getSupply() const {
    return supply;
};

Am I completely off track here, am i missing something or is this type of situtation something normal?

2 Answers 2

2

To increase readability you can change *s to ->:

if(it->first->getDestination()->getDemand() > it->first->getDeparture()->getSupply())

Also, if you aren't going to give up ownership of that object (and you aren't, in this case) it is better to return by const reference:

const Departure& Route::getDeparture() const {
  return *departure;
};

and use ., not ->:

if(it->first->getDestination().getDemand() > it->first->getDeparture().getSupply())
Sign up to request clarification or add additional context in comments.

Comments

2

instead of (*p).x write p->x.

1 Comment

and just chain as iterator->member->method1->method2 etcetera?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.