James Delaney
James Delaney

Reputation: 35

C++ variables passed to constructor are not being passed correctly

I am just trying to get set up with some simple classes in C++. I am trying to create an Order type that takes in a price (double), quantity (int) and a style (std::string)

Here is my order.h

#ifndef ORDER_H
#define ORDER_H

#include <string>
#include <iostream>


class Order {
    private:
        double limit_price;
        int quantity;
        std::string style;
    public:
        Order();
        Order(double price, int quantity, std::string style);

        void print_price();
        void print();
};
#endif

My implementation in order.cpp.

#include "order.h"
#include <iostream>


Order::Order(){
    limit_price = 0;
    quantity = 0;
    style = "bid";
}


Order::Order(double price, int quantity, std::string style){
    limit_price = price;
    quantity = quantity;
    style = style;
}

void Order::print_price(){
    std::cout << "limit_price = " << limit_price << std::endl;
}

void Order::print(){
    std::cout << style << " " << quantity << "@" << limit_price << std::endl;
}

And here is my simple test code.

#include "order.cpp"
#include <iostream>
#include <string>

int main(){

    Order null_order = Order();
    Order order = Order(12.3, 2, "bid");

    null_order.print();
    order.print();

    return 0;
}

However, for a reason I don't understand, when I run I run my test file, instead of getting

bid 0@0
bid [email protected]

As I would have expected, I get something like the following.

bid 0@0
 [email protected]

Where the large negative number changes on each run.

Upvotes: 0

Views: 140

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122457

In your constructor the name of the parameters shadow the members:

Order::Order(double price, int quantity, std::string style){
    limit_price = price;
    quantity = quantity;
    style = style;
}

What do you think quantity is in the second line? Why should it something different on the left hand side than on the right hand side?

quantity refers to the parameter.

You can prepend this-> to members to disambiguate, though thats rather uncommon. In such cases, better rename either of them.

Anyhow you should initialize members rather than assign in the body of the constructor. Members are initialized before the body of the constructor is executed. One way to initialize members is the member initializer list:

Order::Order(double p, int q, std::string s) : limit_price(p),quantity(q),style(s)
{ /* empty body */ }

And because in the initializer list there is no danger of ambiguity we can use the same name for parameters as for the members:

Order::Order(double limit_price, int quantity, std::string style) : limit_price(limit_price),quantity(quantity),style(style)
{}

Upvotes: 2

Related Questions