Bump the Trump
Bump the Trump

Reputation: 13

Var members in a class

I'll try and explain it more clearly with a example. I have a Square and I want to be able to initialise it with variable dimensions such as

(width,length) = (int, int) or (double, int) or (double, double) etc..

I know that if I wanted my square to have integer sides I would just declare it as int width and int height but how do I declare it so it can take many forms ?

eg:

header.h

    class Square 
    {
        public:
            // Constructor : Initialise dimensions
            Square();

            // Set dimensions
            template< typename T1, typename T2>
            setDim(T1 x, T2 y);

        private:
            // Is this right ????
            template <typename T> T width;
            template <typename T> T height;
    };

Moreover, if I do create the square how would I initialise the variables to be 0.

e.g:

src.cpp

Square::Square()
{
    // Would this be correct ???
    width = 0;
    height = 0;
}

Upvotes: 0

Views: 67

Answers (1)

user1812457
user1812457

Reputation:

It is doable, you need however two different types for the width and height, if I understand the question correctly (and note that this is a rectangle, not a square, technically speaking).

#include <iostream>

template <typename W, typename H>
class Rect {
    W width;
    H height;
public:
    Rect(const W w, const H h): width(w), height(h) {}
    Rect(): width(0), height(0) {}
    W get_width() { return width; }
    H get_height() { return height; }
};

template <typename W, typename H>
void show_rect(Rect<W, H> r)
{
    std::cout << r.get_width()
              << "x"
              << r.get_height()
              << "="
              << r.get_width() * r.get_height()
              << std::endl;
}

int main()
{
    show_rect(Rect<int, int>{});
    show_rect(Rect<double, long>{0.3, 8});
}

You can see how you can overload the constructor to initialize with default values. You also see how you can write a function that takes an object of that class as an argument.

With this, I get:

$ make rect
g++ -std=c++14 -pedantic -Wall -O2    rect.cpp   -o rect
$ ./rect
0x0=0
0.3x8=2.4

But I am really not sure about the wisdom of doing it like this. I am sure someone will explain in the comments :)

Upvotes: 1

Related Questions