second Constructor called in c++ ( wrong output) - c++

I am trying to do a simple thing but suddenly stuck in between .
Here in my code I am trying to call a constructor in which i would only pass the length, my first constructor initializes an array of size = length with all elements 0.
Then i am passing the array to the constructor to give the previously defined array its values
here is the sample :
class myvector
{
int *arr;
int length;
public :
myvector(int);
myvector(int *);
};
myvector :: myvector (int len)
{
arr = new int [length = len];
for ( int i=0;i< length;i++)
{
arr[i] = 0;
}
}
myvector :: myvector ( int *ex)
{
for ( int i=0;i< length;i++)
{
cout << ex[i] << " " << length <<" ";
arr[i] = ex[i];
cout << arr[i]<< " ";
}
}
int main()
{
myvector v1(5);
int x[5] = {2,3,4,45,6};
v1 = x;
}
Here in my second constructor length which was defined in first constrcutor lost its values , also array arr loses its values
Did I do something ?
Please elaborate me on this

I don't think you quite get what the circumstances are in which constructors are invoked. The line v1 = x doesn't put the values into the memory allocated during the first constructor call. Rather, it constructs a new myvector (using the second constructor) and copies it into v1. The stuff you do during the first constructor call is lost.
It sounds like you want to define an assignment operator, not a constructor taking an int* argument. Also, in general you should declare single-argument constructors as explicit to prevent this sort of thing from happening accidentally.

First of all, when specifying a size of array like this, you should provide a constant value. See here. And I really encourage you to use std::vector<> for such tasks.
But anyway, like Sneftel mentioned, seems like you want to define an assignment operator (see here for more information about overloading operators in tasks like yours).
Here how I'd implemented it(NOT and ideal solution, but it works, and gives a basic idea):
#include <iostream>
using namespace std;
class myvector
{
int *arr;
int length;
public :
//I completely removed second constructor
myvector(int);
~myvector();
void operator=(const int* otherArray);
void printArray();
};
myvector::myvector (int len)
{
length = len;
arr = new int[length]; // This is the way, how you can handle a non constant array sizes
for ( int i=0;i< length;i++)
{
arr[i] = 0;
}
}
void myvector::printArray()
{
for(unsigned i = 0; i < length; ++i)
cout<<"arr["<<i<<"] = "<<arr[i]<<endl;
}
//Here's an overloaded '=' operator.
//int x[5] = {2,3,4,45,6};
//myvector v;
//v = x; - here this function is called
void myvector::operator=(const int* otherArray)
{
for(unsigned i = 0; i < length; ++i)
arr[i] = otherArray[i];
}
myvector::~myvector()
{
delete []arr; // You should ALWAYS delete what you allocated with new
}
int main()
{
myvector v1(5);
int x[5] = {2,3,4,45,6};
v1 = x;
v1.printArray();
}

Related

What ways are there to call a constructor in C++?

//I have a for loop that should construct an array of a certain class "Line" from two arrays of floats
for (int i=0; i<length; i++) Linearray[i](a[i], b[i]);
//my constructor function for line is:
pine::pine(float a, float b) {
st = a;
e = b;
}
//the error I'm getting is that I have no call operator defined.
//It's a little complicated to explain, so say all I can use is this constructor to fill that array.
//also assume arrays a and b are full of floats.
This Linearray[i](a[i], b[i]); tries to call the call operator operator()() (see also What are C++ functors and their uses?) from the Line class (which you probably haven't defined, hence the error) at the ith element in that list. You'd need to assign a new instance to call a constructor there:
Linearray[i] = Line(a[i], b[i]);
Although your question is already answered by Timo. Here is another way to achieve same goal
#include <iostream>
using namespace std;
class Line{
private:
int start, end;
public:
Line(){}
Line(float a, float b) {
start = a;
end = b;
}
};
int main() {
std::cout << "Hello World!\n";
int N = 5;
Line * arr = (Line*)malloc(sizeof(Line) * N);
for(auto i=0; i<N; i++){
arr[i] = Line(5,6);
}
}

Having a problem with getting the right value with private variable

This is a program that takes an array and print the sum of the odd (named m_sumOdd) and even (named m_sumEven) numbers of that array using class. However when i run it and enter some values like (4, 6, 9, 3, 1) the m_sumEven returns 10 and m_sumOdd returns 2037769787. What's the problem with m_sumOdd ?
#include <iostream>
#include <string>
class myClass {
private:
int m_sumEven;
int m_sumOdd;
public:
myClass() {
m_sumEven = 0;
m_sumOdd = 0;
}
myClass(int arr[]) {
for (int i = 0; i < 5; i++)
{
if (arr[i] % 2 == 0) {
m_sumEven += arr[i];
}
else if (arr[i] % 2 != 0) {
m_sumOdd += arr[i];
}
}
print();
}
void print() {
std::cout << m_sumEven << "\t" << m_sumOdd << std::endl;
}
};
int main(){
int main_arr[5];
for (int j = 0; j < 5; j++)
{
std::cin >> main_arr[j];
}
myClass obj(main_arr);
std::cin.get();
}
From your comment:
the problem is from my uni textbook and it specify that the private variables shall be initialized in the default constructor and the other constructor find the sum
I'm not sure what solution the textbook is looking for, but there is a mechanism that allows one constructor to use another.
class myClass {
private:
int m_sumEven;
int m_sumOdd;
public:
myClass() {
m_sumEven = 0;
m_sumOdd = 0;
}
myClass(int arr[]): myClass() { // <-------
....
This is called delegating constructors. This makes your myClass(int arr[]) constructor use the myClass() constructor before continuing on.
When you do not initialize your variable in C++, the default value of that variable is whatever garbage value happens to already be in that memory location. So if you initialize your privates variables as zeros (as in your non-parameterized constructor), your problem will be solved.
The second constructor doesn't initialize the private variables like the first one.
m_sumEven = 0;
m_sumOdd = 0;
Put these to the second constructor as well.
Even better, put them at the declaration:
int m_sumEven = 0;
int m_sumOdd = 0;
And now you don't need the first constructor.
Unrelated: consider using std::initializer_list instead. This provides you a safe way to know how many items are passed to the constructor, while now you have a fixed 5 in mind which may change later.

how to copy Int array to int pointer using constructor in C++

I am trying to insert int array x to int *v. here is my code . please provide me with optimal solutions and the reason behind it.
there is an error in this line. Instead of copying array value its taking garbage value. line v1=x;
class vector
{
int *v;
int size;
public:
vector(int m)
{
v = new int[size = m];
for (int i = 0; i < size; i++)
v[i] = 0;
}
vector(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
}
int operator *(vector &y)
{
int sum = 0;
for (int i = 0; i < size; i++)
sum += v[i] * y.v[i];
return sum;
}
void disp()
{
for (int i = 0; i < size; i++)
cout << v[i] << " ";
cout << "\n";
}
};
int main()
{
clrscr();
int x[3] = { 1,2,3 };
int y[3] = { 4,5,6 };
vector v1(3);
//v1.disp();
vector v2(3);
v2.disp();
v1 = x;
v1.disp();
//v2=y;
v2.disp();
int r = v1 * v2;
cout << "R = " << r;
getch();
return 0;
}
You forgot to add the assignment operator in your vector class:
vector & operator=(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
return *this;
}
In the the line
v1=x;
May be, you are expecting it to invoke the second constructor which takes int* as argument. But it won't happen.
It can be seen as Type Conversion from Basic type to Class type. where we expect appropriate constructor will get invoked.
see http://www.hexainclude.com/basic-to-class-type-conversion/
But remember, Constructor will be invoked only once after the creation of object.
Here, in the line
vector v1(3);
the first constructor was already invoked. Then the line
v1=x;
won't invoke the second constructor now.
For every class, = operator is default overloaded . That is the reason why we can easily assign objects to one another.
Therefore, the line v1=x invokes default overloaded assignment = operator.
Here, it treats address of array x i.e., &x[0] as address of class object. As it is not address of vector class object
=> it results a Segmentation fault.
YOUR ANSWER
To assign int array to int pointer i.e., to the member variable int* v of the vector class,
overload assignment operator = inside the class .
or
Initialize the class object to array in first line itself. i.e.,
vector v1=x; // modify the class constructor to have size as a constant.

operator overloading in c++ - A query

I was reading a book on operator overloading in c++ and I encountered the following code:
class Array {
...
public:
Array & operator << ( int x) {
// insert x at the end of the array
}
};
Next It says: that overloading of the form a << x << y << z ;
wll not workSo It suggests that second invocation is treated as :( (a << x)<< y ) << z .so it recommends using return *this;
But I am not getting how return *this functions here? Please help!Here is the entire code:
#include <iostream>
#include <cstdlib>
using namespace std;
class Array {
int *a;
int capacity;
int size;
int incr;
public:
Array (int c=10) {
a = new int[c];
capacity = c;
for (int i=0; i<c; i++) a[i]=0;
size=0;
incr = c;
}
Array &operator << (int x) {
if(size<capacity) a[size++] = x;
else {
int *tmp = new int [capacity+incr];
for (int i=0; i<size; i++) tmp[i]=a[i];
delete[] a;
a = tmp;
a[size++]=x;
capacity = capacity+incr;
}
return *this;
};
int operator [] (int i) {
if(i<size) return a[i];
};
};
int main (int argc, char *argv[]) {
int s = atoi (argv[1]);
Array A (s);
for (int i=0; i<s; i++) A << i << i+1;
for (int i=0; i<s; i++) cout << A[i] << endl;
}
This really has nothing to do with operator overloading. It's called chaining and it's easier to explain using regular member functions. Suppose you defined a member function called insert like this:
Array& insert(int x) {
// insert x at the end of the array
return *this;
}
The return *this will return a reference to the current object so that you can chain calls like this:
Array a;
a.insert(0).insert(1).insert(2);
Which is essentially equivalent to:
Array a;
a.insert(0);
a.insert(1);
a.insert(2);
Each call to insert() will return a reference to the original object, allowing other calls to be made using that returned reference. You can overload the << operator to do the same thing:
Array& operator<<(int x) {
// insert x at the end of the array
return *this;
}
Now you can chain calls like this:
Array a;
a << 0 << 1 << 2;
You may be getting confused because of the spacing of Array &operator <<. The return value of the function is Array&, a reference to the array object.
Here's an example. In your call A << i << i+1, the A << i is called first and a reference to the updated A is returned. Next A << i+1 is called, with that new reference.
Yes everything is ok with your code. operator << in your semantics will and returning refference to same object which called it. You can see same in code of operator << of std::ostream and operator >> of std::istream.

Operator Overloading

I'm new to C++, this is my first week since the upgrade from fortran. Sorry if this is a simple question, but could someone help me with operator overloading. I have written a program which has two classes. One object contains a vector and two scalars, the other class simply contains the first object. In a test implementation of this code I suspect the operator overloading to be at fault. The program tries to accomplish the following goals:
1) Initialize first structure.
2) Initialize a second structure containing the initialized first structure. After this is imported, the value val0 = 10 is added to every element of the vector in the enclosing structure, structure2.structure1 .
3) Output structure1 and structure2 variables to compare.
For this simple program my output is:
100
100
0
0
0 0 10
1 1 11
2 2 12
3 3 13
...
I was expecting:
100
100
0
10
0 0 10
1 1 11
2 2 12
3 3 13
...
Clearly my overloaded = operator is copying my vector properly, but one of the scalars? Could someone help?
#include <iostream>
using namespace std;
typedef double* doublevec;
// This first class contains a vector, a scalar N representing the size of the vector, and another scalar used for intializing the vector.
typedef class Structure1
{
int N, vec0;
doublevec vec;
public:
// Constructor and copy constructor.
Structure1(int Nin, int vecin) : N(Nin), vec0(vecin) { vec = new double [N]; for(int i = 0; i < N; i++) { vec[i] = i + vec0; } }
Structure1(const Structure1& structurein);
// Accessor functions:
int get_vec0() { return vec0; }
int get_N() { return N; }
doublevec get_vec() { return vec; }
// Overide equivalence operator:
Structure1& operator=(const Structure1& right)
{
//Handle Self-Assignment
if (this == &right) return *this;
N = right.N;
vec0 = right.vec0;
for (int i = 0; i < N; i++)
{
vec[i] = right.vec[i];
}
return *this;
}
// Destructor:
~Structure1() { delete []vec; }
} Structure1;
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for(int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
}
// This class just contains the first structure.
typedef class Structure2
{
Structure1 structure;
// Mutator Function:
void mutate_structure();
public:
// Constructor:
Structure2(const Structure1& structurein) : structure(structurein) { mutate_structure(); }
// Accessor Function:
Structure1 get_structure() { return structure; }
// Destructor:
~Structure2() {}
} Structure2;
void Structure2::mutate_structure()
{
int N = structure.get_N();
Structure1 tempstruct(N,10);
structure = tempstruct;
}
int main (int argc, char * const argv[])
{
const int N = 100;
Structure1 structure1(N,0);
Structure2 structure2(structure1);
cout << structure1.get_N() << endl;
cout << structure2.get_structure().get_N() << endl;
cout << structure1.get_vec0() << endl;
cout << structure2.get_structure().get_vec0() << endl;
for(int i = 0; i < N; i++)
{
cout << i << " " << structure1.get_vec()[i] << " " << structure2.get_structure().get_vec()[i] << endl;
}
return 0;
}
it looks like vec0 isn't initialized by your copy constructor...
Try modifying your copy constructor to:
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for (int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
// ADD THIS LINE
vec0 = structurein.vec0;
}
Your copy-constructor Structure1::Structure1(const Structure1 &) doesn't copy vec0. It's not getting initialised at all, so gets whatever is in memory.
Also, you might want to check Structure1's operator=. If you assign a large vector to a small vector, then you'll potentially overflow the array in the destination. You might need to reallocate memory in operator=.