C++ Default constructor not available - c++

I'm currently learning C++ and reading through "C++ Primer 5th Edition". I just started learning about constructors and I'm having a bit of a problem that I can't figure out.
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <string>
struct Sales_data
{
//default constructor
Sales_data(const std::string &s, unsigned n, double p):
bookNo(s), units_sold(n), revenue(p*n) { }
//new members: operations on Sales_data objects
std::string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
double avg_price() const;
//data members
std::string bookNo;
unsigned units_sold;
double revenue;
};
I'm pretty sure that the default constructor I wrote is correct (considering it's the one written in the book), but obviously I'm missing something here. I don't see any syntax errors or anything and all of the built-in members are being initialized so I have no idea what's wrong.
EDIT :
I just found out that it's not my header file giving the error, it's actually my source file. When I create a Sales_data object like:
Sales_data total;
it gives me the "No appropriate default constructor available" error. I'm still unsure as to what's wrong considering the author gave three ways to write a default constructor, these are them:
struct Sales_data {
// constructors added
Sales_data() = default; //Number 1
Sales_data(const std::string &s): bookNo(s) { } //Number 2
Sales_data(const std::string &s, unsigned n, double p): //Number 3
bookNo(s), units_sold(n), revenue(p*n) { }
If those aren't default constructors, then what exactly are they/is their purpose?

A default constructor is a constructor that can be called without passing any argument.
This means that it must take no parameters or that all of them must have a default value.
The default constructor is needed for example when you write
MyClass x;
because the compiler must be able to generate code to build such an object without any arguments.
Also standard containers may require a default constructor depending on how you use them: for example if you use std::vector::resize the library can be asked to increase the size of a vector containing your class instances, thus it must be able to create elements without providing any argument.

The problem isn't related to default constructors. The problem indeed is in Sales_data total;. What's the book number, sales price and number sold for total? You must provide them when constructing total.

The constructor of your class takes three parameters, those must be provided when you try to construct an object. Your current variable declaration doesn't provide any parameters:
Sales_data total;
Because there are no parameters provided, the compiler tries to use a constructor that doesn't take any parameters. Such a constructor is also called "default constructor". Your class doesn't have a constructor without parameters, so this doesn't work.
To use the existing constructor, you have to provide the parameters when you create the object:
Sales_data total("books", 28, 15.99);
Alternatively you could add a constructor to Sales_data that doesn't take any parameters (a default constructor), and initializes the class with some default values.

Related

Default constructor for struct with Long and pointer

I am in the process of learning c++.
I have a struct like this:
struct Info {
const Long rate;
A* ptr;
}
I have a constructor which takes all the arguments as its parameters to initialize the struct. However, this struct is part of another class which will be serialized using boost serialization. In order to serialize that class I would need a default constructor for this struct. However, when I try to write a default constructor such as
Info () {
}
I get an error C2758 that the member rate should be initialized in the constructor.
How to get a default constructor for such a struct which I can use to serialize my class.
You need to initialize the constant value, so:
Info () : rate(0) {
}
The error is probably due to the fact that your Long class does not have a default constructor either.
There are two ways of fixing this:
Add a default constructor to Long, or
Add rate to the initialization list of Info's constructor.
You can see the msdn documentation for C2758 for a description of the error.
In basic term's, a const variable must be initialised in all constructors. The compiler enforces that any built in type or pointer member that is const must be initialised when the object is constructed, as you won't get a chance to give it a meaningful value after construction ( if you could change it after it was created, how is it const ? ).
Also, as a general rule of thumb, it is always a good idea to initialise members that don't have a default constructor ( built in types, pointers, and objects without default constructors ) to something, in all your class constructors. Otherwise they will either be initialised to some random value ( primitives or pointers ), or you will get a compile error ( objects without default constructors ).
Info()
: rate(0)
, ptr(nullptr)
{
}
If you are assigning values to some of your parameters from constructor arguments, don't forget to assign a value to the other members as well.
Info( Long rate)
: rate( rate )
, ptr(nullptr)
{
}
try this :
struct Info {
const Long rate;
A* ptr;
Info():rate(0){} // as Matthew guessed, call the correct Long constructor
// or define a default constructor for Long
};

Constructor initialization with arguments

Another question from reading "Accelerated C++" by Andrew Koenig and Barbara E. Moo, and I'm at the chapter about constructors (5.1), using the example as before.
They write
we'll want to define two constructors: the first constructor takes no arguments and creates an empty Student_info object; the second takes a reference to an input stream and initializes the object by reading a student record from that stream.
leading to the example of using Student_info::Student_info(istream& is) {read(is);} as the second constructor which
delegates the real work to the read function. [...] read immediately gives these variables new values.
The Student_info class is
class Student_info {
public:
std::string name() const (return n;}
bool valid() const {return !homework.empty();}
std::istream& read(std::istream&);
double grade() const;
private:
std::string n;
double midterm, final;
std::vector<double> homework;
};
Since read is already defined as a function under the Student_info class, why is there a need to use a second constructor - isn't this double work? Why not just use the default constructor, and then the function since both are already defined?
It isn't double work on the contrary it simplifies the object initialization for the caller who instantiates the class
If you create the class with a single constructor every time you have to do
std::istream is = std::cin;
Student_info si();
si.read(is);
// si.foo();
// si.bar();
// si.baz();
Maybe some other operations can be added that can be done in constructor. So you don't have to write them again when you need to instantiate the class. If you create 10 instances you will have to write
( 10 -1 = ) 9 more lines and this isn't a good approach for OOP
Student_info::Student_info(istream& is)
{
read(is);
//foo();
//bar();
//baz();
}
But when you define two constructors like above, you can use the class like
std::istream is = std::cin;
Student_info si(is);
One of the main goals of OOP is writing reusable and not self repeating code and another goal is seperation of concerns. In many cases person who instantiates the object doesn't need to know implementation details of the class.
On your example read function can be private when its called inside constructor. This reaches us another concept of OOP Encapsulation
Finally this isn't double work and its a good approach for software design
My question is since read is already defined as a function under the Student_info class, why is there a need to use a second constructor - isn't this double work?
The second constructor takes an argument from the caller and passes it on to the read function. This allows you to directly instantiate a Student_info with an std::istream.
std::istream is = ....;
Student_info si(is); // internally calls read(is)
as opposed to
std::istream is = ....;
Student_info si;
si.read(is); // how could we use is if this call isn't made? Now we have to read some docs...
Why not just use the default constructor, and then the function since both are already defined?
Because it is better to construct objects such that they are in a coherent, useful state, rather than construct them first and then initialize them. This means users of the objects do not have to worry about whether the thing can be used or must first be initialized. For example, this function takes a reference to a Student_info:
void foo(const Student_into& si)
{
// we want to use si in a way that might require that it has been
// initialized with an istream
si.doSomethingInvolvingInputStream(); // Wait, what if the stream hasn't been read in?
// Now we need a means to check that!
}
Ideally, foo should not have to worry about the object has been "initialized" or made valid.

Creating a copy constructor with arguements for a class

I have created a simple class that takes an argument to the constructor as shown below.
class Jam
{
int age;
std::string name;
Jam *jam;
Jam(std::string argName) {
name = argName;
}
};
It takes the argument and initializes the Jam's name to the parameter passed. The only problem is that I'd like to be able to pass another copy of Jam to the constructor so I can initialize its pointer to an existing class by copying the values. Normally in C++ you could specify Jam *jam = new Jam(existingJam); and it would be copied by default, but since I already have std::string argName as a parameter, it refuses to let me do this.
I read an article here that explains how to create your own copy constructor, but it is rather tedious and involves copying each class member individually which seems like it would not make much sense for a class with 10+ data members. Is there a better way to do this than initializing each member individually?
Jam::Jam(std::string argName, Jam *argJam)
{
age = argJam->age;
//etc...
}
[It's quite possible I don't understand what you're asking, but here goes...]
The compiler provides a copy constructor if you don't write one yourself. Its behaviour is to copy each member variable in turn.

default constructor that has the option to take in a parameter?

Is it possible to have 1 constructor have the option of being a default constructor if a parameter is not passed in.
Example, instead of having 2 constructors, where 1 is the default constructor and another is a constructor that initializes numbers passed in, is it possible to only have 1 constructor that if a value is passed in, set that value to a member function, and if no value is passed in, set the member function to a number.
example:
WEIGHT.H file:
class Weight
{
public:
Weight() { size = 0; }
Weight(int a) : size(a) {}
int size;
};
MAIN.CPP file:
int main(void)
{
Weight w1;
Weight w2(100);
}
I've been working on different school projects and they all require to have different types of constructors, and i'm wondering if there is a way to only have it once so it saves time.
Thanks for the help.
Yes, a constructor parameter may have a default argument, just like other functions can. If all of the parameters of a constructor have default arguments, the constructor is also a default constructor. So, for example,
class Weight
{
public:
explicit Weight(int a = 0) : size(a) { }
int size;
};
This constructor may be called with a single argument or with no arguments; if it is called with no arguments, 0 is used as the argument for the a parameter.
Note that I've also declared this constructor explicit. If you have a constructor that may be called with a single argument, you should always declare it explicit to prevent unwanted implicit conversions from occurring unless you really want the constructor to be a converting constructor.
(If you aren't familiar yet with converting constructors or implicit conversions, that's okay; just following this rule is sufficient for most of the code you'll ever write.)
Yes its possible as suggested by James but as you know if you are not defining the Default constructor the compiler would take over the definition part if you have not provided any constructor definition.
Its not an issue as such but its a better practice to define the Default constructor for proper initialization of values.
Google C++ Style guide also recommends it.

Classes in C++ with Ctor [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
The Definitive C++ Book Guide and List
i have a lot of questions about declaration and implementation, according to most (books, tutorials, blog entries) a class declaration with constructor, methods and member functions:
class Book
{
public:
Book(const string & author_,
const string & title_,
const string & publisher_,
double price_,
double weight_);
string getName()
{
string name;
name = author + ": " + title;
return name.substr(0, 40);
}
double getPrice();
double getWeight();
private:
string author, title, publisher;
double price, weight;
};
i understand all the the access level, the Constructor, reference operator (pointer too!), the pointer operator, but when I read things less trivial like:
class Type
{
public:
enum TypeT {stringT, intT, doubleT, unknownT};
// 1. which means "explicit"?
// 2. what's ": typeId(typeId_)"? after the Ctor declaration
explicit Type(TypeT typeId_) : typeId(typeId_) {}
// 3. "const" after the declaration which means?
BaseValue * newValue() const
{
return prototypes[typeId]->clone();
}
TypeT getType() const
{
return typeId;
}
static void init();
{
prototypes[stringT] = new Value<string>("");
prototypes[intT] = new Value<int>(0);
prototypes[doubleT] = new Value<double>(0);
}
private:
TypeT typeId;
static vector<BaseValue *> prototypes;
};
I feel lost and really have not found clear information about the above points.
Addition to answering my question, if you know somewhere where they have these "tricks" of language
A good introductory book to C++ should answer your questions.
explicit means the constructor must be mentioned explicitely in the code, the type cannot be constructed automatically from another type when required.
Member initialization. The class member is not constructed with its default constructor, but rather the arguments given here.
The method can be called on a const object.
1) By default, c++ will assume that any constructor taking one argument of another type can be used as an "implicit conversion" from the arg's type to the constructor's type; in your example, this would allow you to pass a TypeT into any function expecting a Type, and the constructor would assume you want it to run the Type(TypeT) constructor before actually calling the function.
the explicit keyword prevents that from happening; it tells the compiler that you only want that constructor run when you specifically call it.
2) in between the prototype of the constructor and its body, you can (and, for the most part, should) provide an initializer list; When a constructor is run, the system initializes every parent, then every contained member before running the body of the constructor. The initializer list tells the compiler which constructor you want to be run on a given member variable; in the case of your example, you're running the copy constructor on typeId.
If you don't provide an entry in the initializer list for a given member, the system will simply run the default constructor on that member before entering the body of the original class. This means that, should you assign to the member within the body of your class constructor, you'll be writing to that member's memory twice. This is necessary sometimes, but for many cases is simply wasteful.
3) const at the end of a method prototype makes a guarantee to the compiler that that method will not modify any of the member variables within the class instance when it is called. This allows the method to be called on const instances of your class, and, just like placing const on any variables that will remain unchanged, should be done whenever possible to guarrantee correctness and type safety.
As for which books to read, the link in your question's comments would be a good place to start. Since you seem to understand the barebones basics of the language, I would recommend starting with "Effective C++". It presents a list of best practices for C++, and is aimed at someone who understands the C aspects of the language.