Is it possible to initialize a vector member with the initialization list of the constructor. I give some incorrect codes below.
#ifndef _CLASSA_H_
#define _CLASSA_H_
#include <iostream>
#include <vector>
#include <string>
class CA{
public:
CA();
~CA();
private:
std::vector<int> mCount;
std::vector<string> mTitle;
};
The implementation of the constructor in .cpp file
// I want to do it this way
#pragma once
#include "classa.h"
// Constructor
CA::CA(int pCount, std::string pTitle) :mCount(pCount), mTitle(pTitle)
{
}
// Destructor
CA::~CA()
{
}
in main file
#include "classa.h"
int main()
{
CA A1(25, "abcd");
return 0;
}
If you want to initialize the vector members with the the parameters passed to CA::CA as elements, you can use list initialization (since C++11), for which the constructor of std::vector taking std::initializer_list will be used for initialization. e.g.
CA::CA(int pCount, std::string pTitle) :mCount{pCount}, mTitle{pTitle}
// ~ ~ ~ ~
{
// now mCount contains 1 element with value 25,
// mTitle consains 1 element with value "abcd"
}
Related
I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?
#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>
using namespace std;
class vec {
private:
// Variable to store the number of elements contained in this vec.
size_t elements;
// Pointer to store the address of the dynamically allocated memory.
double *data;
public:
/*
* Constructor to create a vec variable with the contents of 'ilist'.
*/
vec(initializer_list<double> ilist);
}
int main() {
vec x = { 1, 2, 3 }; // should call to the constructor
return 0;
}
initializer_list has size method, it gives you information how many elements must be allocated by new, so it could be:
vec(initializer_list<double> ilist)
{
elements = ilist.size();
data = new double[ ilist.size() ];
std::copy(ilist.begin(),ilist.end(),data);
}
Use a standard std::vector container instead of a raw pointer. std::vector is a wrapper for a dynamic array, and it has a constructor that accepts a std::initializer_list as input.
#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;
class vec {
private:
vector<double> data;
public:
vec(initializer_list<double> ilist) : data(ilist) {}
};
How to combine array.h, array.cpp and main.cpp files together? I am getting an error while compiling main.cpp, that class Array is not declared in scope.
main.cpp:
#include<iostream>
#include "Array.h"
#include "Array.cpp"
using namespace std;
int main(){
Array a;
a.Array();
return EXIT_SUCCESS;
}
Array.h:
#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
class Array{
private:
int data;// The value or data stored in the node
int ArraySize;//Size of array
int* array;
public:
Array();
};
#endif
Array.cpp:
#include <iostream>
#include <cstdlib>
using namespace std;
#include "Array.h" // user defined header file
Array::Array(){ //initialise array
cout << "Initialising array elements----------------->"<< endl;
for (int i=0; i < 4; i++){
//array[i]= 1;
cout << i << endl;
}
}
ERROR message: invalid use of 'class Array'
The problem you have is that you are attempting to call the constructor of a class on an instance of that class:
Array a;
a.Array();
When you declare a function the same name as a class, you are creating a constructor for that class.
class Array
{
public:
// Default constructor
Array();
// This is a function you can call
void PrintData();
}
You can't call this function though. It's called automatically when you create an object of class Array:
Array a; // This will call Array's constructor
a.PrintData(); // This will call the function PrintData on the object 'a'
I'm trying to use arrays with unique_ptr with no success.
What is the correct way to declare a unique_ptr of some size?
(size is some paramter).
unique_ptr<A[]> ptr = make_unique<A[]>(size);
Here's an example:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
This is not working, however, if I delete the constructor of A, it works.
I want the 3 to represent the size of the array, and not an argument to A's constructor, how do I make that happen?
This is not working, however, if I delete the constructor of A, it
works.
When you removed the user defined constructor, the compiler implicitly generates a default one. When you provide a user defined constructor, the compiler doesn't implicitly generate a default constructor.
std::make_unique<T[]> requires the use of default constructors...
So, provide one, and all should work well
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A() = default;
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
Dialog.h
#include "WBasic.h"
#include "WButton.h"
#include "WData.h"
#ifndef WDIALOG_H_INCLUDED
#define WDIALOG_H_INCLUDED
class WDialog : public WBasic
{
private:
WButton wB;
WData wD;
public:
//Constructor
WDialog(const int& e = 0, const WButton& = WButton(0,0), const WData& = WData(0,0,0));
~WDialog();
};
#endif // WDIALOG_H_INCLUDED
Dialog.cpp
#include <iostream>
#include "WDialog.h"
WDialog::WDialog(const int& e, const WButton& WBUTTON, const WData& WDATA) :
WBasic(e), wB(WBUTTON), wD(WDATA)
{
}
The code above works great, however I'm trying to make "WButton wB" a vector changing it to"WButton wB[3];"
class WDialog : public WBasic
{
private:
WButton wB[3];
WData wD;
};
But then I've no idea how deal with the Constructor.
You can use vector to solve this problem.
I have written a small example below.
#include <iostream>
#include <vector>
using namespace std;
class A{
};
class B{
public:
B():vec (4,A())
{
}
private :
vector<A> vec;
};
int main() {
// your code goes here
B obj();
return 0;
}
You can observe how I have initialized vector vec with three class A object.
In my opinion if you can (your compiler support C++11) prefer std::array
#include <array>
std::array<WButton, 3> wB;
Then in your contructor use an initializer list:
WBasic(e),
wB{WButton(...), WButton(...), WButton(...)},
wD(WDATA)
I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.
I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:
...error: '_bookingVector' was not declared in this scope|
I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):
Schedule::Schedule() : _bookingVector()
{ }
Is my syntax wrong? Or are vectors initialized differently?
Here is my code:
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>
using namespace std;
class Schedule
{
public:
Schedule();
void AddBooking(int bday, int btime, int btrainer, int bid);
void RemoveBooking(int bday, int btime);
void DisplaySchedule();
void DisplayAvailableTimeSlots();
//For Testing
void DisplayDebug();
private:
vector<Booking> _bookingVector;
};
#endif // SCHEDULE_H
Schedule.cpp
#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream>
Schedule::Schedule() : _bookingVector()
{ }
void AddBooking(int bday, int btime, int btrainer, int bid){
Booking bookingObject(bday, btime, btrainer, bid);
_bookingVector.push_back(bookingObject);
}
void DisplayDebug(){
for(int i = 0; i < _bookingVector.size(); ++i){
cout << _bookingVecotr[i] << endl;
}
}
I'm very eager to learn what I'm doing wrong and fix it.
The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.
Modify the definitions to be in the scope of the Schedule class thus:
void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
^^^^^^^^^^
void Schedule::DisplayDebug(){ ...
^^^^^^^^^^
Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)
1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.