Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have started doing C++ clases for over 2 weeks now and I have a small problem that i dont know how to solve. I have to make a simple Class with one int parameter. That class needs to work with direct and copying initilaization and needs to print message which initialization is used. For example:
TestClass T(60) //this should print a message "Direct initialization"
TestClass T = 205 // this should print a messagte "Copying initialization"
If you use a constructor with a single variable initialization, then this assignment operation will be done for you automatically. See my code below:
#include<bits/stdc++.h>
using namespace std;
class A {
int x;
public:
A(int xx) {
cout << "Constructor Called" << endl;
x = xx;
}
print() {
cout << "Value of obj is " << x << endl;
}
};
int main() {
A v = 10;
v.print();
}
Because you used initialization constructor, = operator was handled automatically. To prove that it is using the constructor, I used cout in constructor and created and called another printing function.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This code runs fine, when it should have a run-time error, since i haven't instantiated a derived class object.
#include <iostream>
using namespace std;
class Person {
public:
void walk() { cout << "person walking" << endl; }
};
class Employee :public Person {
public:
void work() { cout << "employee working" << endl; }
};
void main() {
Person* p = new Person();
Employee* e = static_cast<Employee*>(p);
e->work();// this is working - but why? it should fail at runtime
}
If static_cast only casting the pointer, how is it possible to call a child member function?
At what point is the child instantiated?
Is static_cast also instantiating objects?
No.
Your assertion that your code should "crash at runtime" is, unfortunately, wrong. Your code exhibits undefined behaviour meaning that it could do literally anything. In this case I expect it works because the address of the function is the same in both objects but really, it could be for any reason.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm reading through my C++ textbook for an upcoming class, and following along an exercise in the book. This exercise compiles and seems to give the results that you would expect, but it seems there is an error though, and I can't figure out how to fix it.
Here is the code.
// Page 706 from text
//Contents of ThisExample.h
class Example
{
int x;
public:
Example(int a){x=a;}
void setValue(int);
void printAddressAndValue();
};
/*
//Contents of ThisExample.cpp
#include "ThisExample.h"
*/
#include <iostream>
using namespace std;
/*********************************************************
* Set value of object.
*********************************************************/
void Example::setValue(int a) // <---------- Doesn't execute
{ // <---------- Doesn't execute
x = a; // <---------- Doesn't execute
} // <---------- Doesn't execute
void Example::printAddressAndValue()
{
cout<< "The object at address " << this << " has "
<< "value "<< (*this).x<<endl;
}
/*
//Contents of main program
#include <iostream>
#include "ThisExample.h"
using namespace std;
*/
int main()
{
Example ob1(10), ob2(20);
// Print the addresses of the two objects
cout<<"Addresses of objects are "<< &ob1 << " and "<<&ob2<<endl;
// Print the addresses and values from within the member function
ob1.printAddressAndValue();
ob2.printAddressAndValue();
return 0;
}
In the book, they talk about replacing
void Example::setValue(int a)
{
x = a;
}
with
void Example::setValue(int a)
{
this->x = x;
}
But when I step through it with a debugger (which I am also new to), I don't see that function ever getting called.
I've tried commenting out the function entirely and it still runs, that's how I know it isn't getting called.
I also tried removing from the class
Example(int a){x=a;}
but then it doesn't compile. Any help? I just want to move along with the textbook, which is called "Starting Out With C++ Early Objects
Judy Walters, Godfrey Muganda, Tony Gaddis" and the exercise is on page 706.
Thanks
It doesn't ever get called, because you never call it.
The only place that the member variable x is set, in this particular example, is in the constructor. And the constructor happens to do so directly, rather than by calling setValue().
You could later call setValue() to change x, but currently you do not.
It's not uncommon to provide functionality that makes sense to be part of the class, even if you're not using that functionality quite yet. Although, unless you're writing a library, you generally wouldn't do too much of writing functionality you don't yet need.
Perhaps later exercises in the textbook involve calling setValue(). I would just continue reading and not worry about this.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming = {{1,"ONE"},{2,"TWO"}};
cout<<naming.numline<<":"<<naming.numname<<std::endl;
return 0;
}
This error occurs:
main.cpp:10:33: error: braces around scalar initializer for type int
} naming = {{1,"ONE"},{2,"TWO"}};
You have
struct naming { … } naming = …
which means you're creating a single naming object. But your initializer
{{1,"ONE"},{2,"TWO"}}
doesn't match that intent.
Looks like you're trying to initialize a collection of naming objects. If that's the case you should make it a std::vector<naming> instead of a single object:
struct naming { … }; // definition of naming
std::vector<naming> namings = {{1, "ONE"}, {2, "TWO"}}; // collection of objects
Then you can access the individual naming objects like so:
// access the first element:
std::cout << namings.at(0).numline << ":" << namings.at(0).numname << std::endl;
// access the second element:
std::cout << namings.at(1).numline << ":" << namings.at(1).numname << std::endl;
Since you want to store two values , you will have to create an array of structure type.
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming[] = {{1,"ONE"},{2,"TWO"}};
cout<<naming[0].numline<<":"<<naming[0].numname<<std::endl;
cout<<naming[1].numline<<":"<<naming[1].numname<<std::endl;
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been trying to figure out the error past an hour, so asking .
Even though I have my parameterized constructor accepting default length,breadth it shows them correctly in same class but returns both of them 0 in derived class box when I am trying to use it there.
#include<iostream>
class rectangle
{
protected :
//int length=12,breadth=13; // LINE A
int length,breadth; // LINE B
public:
rectangle(){} // Empty default constructor
rectangle (int len , int br)
{
length =len ,breadth =br;
}
void area_rect()
{
std::cout << "\n Area is " << (length*breadth);
std::cout << "\n Length,Breadth : " << length << " "<<breadth<< "\n";
}
};
class box : public rectangle
{
int depth;
public:
box() {} // Again empty constructor of derived class
box(int d)
{
depth = d;
}
void area_box()
{
std::cout << "VOLUME IS : "<<(length*breadth*depth)<< "\n";
}
};
int main()
{
rectangle r(10,20);
r.area_rect();
box b(30);
b.area_box();
return 0;
}
-- uncommenting line B, and Commenting A gives
Area is 200
Length,Breadth : 10 20
VOLUME IS : 0
-- uncommenting line A, and Commenting B gives
Area is 200
Length,Breadth : 10 20
VOLUME IS : 4680
You always should initialize simple member variables in the constructor:
rectangle() : length(0), breadth(0) {};
otherwise they stay "uninitialized" which means they have a garbage value.
For object member variables (e.g. if you had std::string color; as another private member variable of your rectangle), the default constructor would have been called.
And the derived class constructor should call (or implicitly calls, if you forget it) the base class constructor:
box () : rectangle () {}
BTW, compile your code with all warnings and debug info (e.g. g++ -Wall -g if using GCC) then use the debugger (e.g. gdb) to run your program step by step and query the various data.
Also, study the source code of some free software written in C++; it will teach you a lot.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
As you probably would be able to tell from my question,, I'm a c++ newbie
I'm not sure what's the right way to copy one string's value to another..
For instance I did this:
std::string x = "this is x";
std::string y = "this is y";
x = y;
No error,, but this does not do anything..
I know there is string::copy... but seems like this function needs buffer size, etc.. which is annoying..
Is there a simple way to do this job in c++?
Thanks
UPDATE!!
Sorry,, I think I simplified my answer too much.....
This is my situation:
class MyClass {
std::string m_str = "OLD STRING";
}
void CopyString(MyClass& c, std::string x) {
c.m_str = x;
}
int main() {
MyClass c;
CopyString(c, "NEW STRING");
std::cout << c.m_str << std::endl; // prints "OLD STRING"!!
}
Your code
std::string x = "this is x";
std::string y = "this is y";
x = y;
is correct, and copies the value of the y variable, to the x variable.
Your assertion
” this does not do anything.
is – happily – incorrect.
when you do x = y, it will copy the value of y into x, thus, make x will be this is y
All though its not the best implementation (get/set methods would be better), you need to make m_str public. When using a class, if you don't set it differently all variables are set to private by default. Change it to this and it should compile and run.
class MyClass {
public:
std::string m_str = "OLD STRING";
};
EDIT: you also forgot your semicolons at the end of your class and copy methods.