Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constructor Definition in C++

I am learning C++ for the first time, and I’m going through "Understanding the C++ Programming Language, Fourth Edition, C++11". I’m having trouble getting some code to compile from an early section.

I’m creating a custom Vector class with some basic functionality using the code below:

#include <iostream>

class Vector {
public:
    Vector(int s) : elem{new double[s]}, sz{s} {}
    double& operator[](int i) { return elem[i]; }
    int size() { return sz; }
private:
    double* elem;
    int sz;
};

double read_and_sum(int s) {
    Vector v(s);
    for (int i=0; i!=v.size(); ++i)
        std::cin>>v[i]; // read into elements

    double sum = 0;
    for (int i=0; i!=v.size(); ++i) 
        sum+=v[i]; // take the sum of the elements

    return sum; 
}

int main() {
    int sum = read_and_sum(5);
    std::cout << sum;
}

When I open the terminal and use g++ to compile the file, I get some errors in my Vector class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

vector2.cpp:5:40: error: expected member name or ';' after declaration specifiers
    Vector(int s) : elem{new double[s]}, sz{s} {}
                                       ^
vector2.cpp:5:25: error: expected '('
    Vector(int s) : elem{new double[s]}, sz{s} {}
                        ^
vector2.cpp:5:39: error: expected ';' after expression
    Vector(int s) : elem{new double[s]}, sz{s} {}

Am I using the wrong syntax to make the Vector class? Everything in it is pretty much identical to the book.

I’ve tried changing the syntax, but continue to get errors, and I’m not really sure what to change since I’m just starting with the language. Is this a problem with the book being C++11 and my compiler doesn’t support that syntax?

>Solution :

The error message is very clear.
Change the line Vector(int s) : elem{new double[s]}, sz{s} { to Vector(int s) : elem(new double[s]), sz(s) {.

Or you can specify option -std=c++11 to adopt c++11’s new features.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading