Home > Software engineering >  why is the address displayed instead of the name?
why is the address displayed instead of the name?

Time:12-12

don't pay too much attention to the logic of the code, quickly made for an easier example!

for example i have a container that contains pointers on my Order, and i have a possibility to show my all orders.I try to do it but i get adrress of idk what

#include <iostream>
#include <list>

class Order {
public:
    static std::list <Order*> orders;
    std::string order;
public:
    Order(std::string ORDER) {
        this->order = ORDER;
    }

to make some orders :


    static void makeOrder(std::string item) {
        Order* order = new Order(item);
        orders.push_back(order);
    }

to show my orders :

    static void showOrder() {
        std::list<Order*>::iterator it;

        for ( it = orders.begin(); it != orders.end(); it   ) {
            std::cout << *it << std::endl;
        }
    }
};

std::list <Order*> Order::orders;


int main() {
    Order::makeOrder("Knife");
    Order::showOrder();
}

how to make the "knife" come out?

CodePudding user response:

You're printing the value of a pointer, which is just a memory address.

std::cout << (*it)->order << std::endl;

CodePudding user response:

Replace std::cout << *it << std::endl; with:

std::cout << (*it)->order << std::endl;

In the above modified statement, *it gives us a pointer to Order (Order*). Next we dereference that pointer which gives us an object of type Order. And finally we access the value of the order data member of that object.

Important

Also, don't forget to free the memory allocated on the heap(using new) using delete. Otherwise, you will have a memory leak in your program.

  •  Tags:  
  • c
  • Related