Old book new questions ;)

Hi there
as it turns out this old book https://goo.gl/s3UGGo is causing me to doubt stuff that is in the book. At back of my mind I have voice whispering "... could this be already replaced by something newer in C++11, C++14 or C++17???"

so I am now at the constructors and I am not sure if this is still valid or is there newer better way of doing it?


1
2
3
4
5
6
7
8
9
10
11
12
13
class Distance 
{
Private:
        int feet;
        float inches;
Public:
Distance() : feet(0), inches(0) // is this still valid way to create constructor?
   {}

//or like this
Distance (int ft, float in) : feet(ft), inches(in)
{}


thanks guys :)
> is this still valid

Yes. Almost everything that was valid in C++98 is also valid in C++11 and later

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace A
{
    class distance // C++98, C++11, C++14, C++17
    {
        private:
            int feet ;
            float inches ;

        public:
            distance() : feet(0), inches(0) {}
            distance( int ft, float in ) : feet(ft), inches(in) {}

    };
}

namespace B
{
    class distance // C++98, C++11, C++14, C++17
    {
        private:
            int feet ;
            float inches ;

        public:
            // also the default constructor
            explicit distance( int ft = 0, float in = 0 ) : feet(ft), inches(in) {}
    };
}

namespace C
{
    class distance // requires C++11 or later
    {
        private:
            int feet = 0 ;
            float inches = 0 ;

        public:
            constexpr distance() = default ;
            constexpr explicit distance( int ft ) : feet{ft} {}
            constexpr distance( int ft, float in ) : feet{ft}, inches{in} {}
    };
}
JLBorges wrote:
1
2
3
constexpr distance() = default ;
constexpr explicit distance( int ft ) : feet{ft} {}
constexpr distance( int ft, float in ) : feet{ft}, inches{in} {}

I just now learned that you can use the default keyword to create a default constructor... Wow.
What does constexpr do with the constructors? I know functions that have a constexpr return type (of a type like int) are evaluated at compile time.
> What does constexpr do with the constructors?

If the class has a trivial destructor (as in the case above), the class is deemed to be a literal type.
Details: http://en.cppreference.com/w/cpp/concept/LiteralType

Objects declared constexpr have their initializer evaluated at compile time; they are basically values kept in the compiler's tables and only emitted into the generated code if needed.
http://www.stroustrup.com/C++11FAQ.html#constexpr
that is amazing @JLBorges thank you :)
Topic archived. No new replies allowed.