Unexpected output value with class constructor and class member variable - c++

I need to understand why x(x + 1) happened only after I get out of the constructor.
class A
{
protected:
int x;
public:
A(int x = 5) : x(x + 1)
{
cout << "In A::A x=" << x << endl;
}
operator int() const { return x; }
};
void main()
{
A a1(10);
cout << a1 << endl ;
}
I was thinking I will get:
In A:: An x=11
11
But somehow I've got:
In A:: An x=10
11

You have two variables named x.
Inside the body of the constructor the argument variable will shadow the member variable. Whenever you use x inside the body of the constructor, it will be the argument, not the member.
To use the member variable you need to explicitly fetch it from the object, like this->x.
General tip: Don't use the same name for symbols in nested scopes. Besides solving this problem, it will also make the code easier to read and understand.

Your parameter is hiding the member variable of the same name - your definition is equivalent to
class A
{
protected:
int y;
public:
A(int x = 5) : y(x + 1)
{
cout << "In A::A x=" << x << endl;
}
operator int() const { return y; }
};
When a parameter has the same name as a member, you need to explicitly refer to the member with this->.
(The initialiser list follows its own rules.)

Related

Code displays "::" on the terminal, cause unknown

using namespace std;
struct A
{
int i;
A(int i_ = 13) : i(i_)
{
cout << _FUNCTION_ << "\n";
}
~A()
{
cout << _FUNCTION_ << "\n";
}
};
int main()
{
A* p = new A;
A a();
return 0;
}
When I run it, the code displays on my terminal "A::A". I get that the first A is called from first FUNCTION for "A* p" , but why does "::" appear? And the last A after "::" is from " A a(); "?
A constructor for a type has the same name as the type itself. :: is the scope resolution operator and is used to name things contained within a named scope, such as a namespace or a type.
The constructor of A is therefore A::A. The first A is the name of the type, and the second is the name of the constructor; the :: is to indicate that the constructor is declared within the scope of the type.
This mirrors the way you would define type members following a declaration with no definition. For example:
struct A
{
int i;
A(int i_ = 13);
~A();
};
// Note how we have to refer to the constructor to define it since we are
// no longer within the scope of A:
A::A(int i_) : i(i_)
{
cout << _FUNCTION_ << "\n";
}
// Similar for the destructor.
A::~A()
{
cout << _FUNCTION_ << "\n";
}
You should only see A::A in your output. Note that you only create one A value here:
A* p = new A;
You never delete p; and so you don't see the matching destructor call (A::~A) in the output.
This line does not create a variable of type A; rather, it declares a function called a that takes no arguments and returns an A value. This function is never invoked (nor defined):
A a();
This is a vexing parse (not to be confused with the most vexing parse). Clearly you intended to declare a variable, but this could be either a function or variable declaration, and the grammar prefers a function declaration.
To fix this, either remove the parens or use C++11's uniform initialization syntax:
A a; // Default initialization
A a{}; // Uniform initialization
_FUNCTION_ is a magic constant, therefore it posts the first "A" (name of the function called. Can't help with the rest though.

data member int reference

I a trying to store int by reference as data member of class.
I expected that is object get int by refernce than if I increase the reference from outside its increase the value inside the object.
class A
{
private :
int& x;
public:
A(int y) : x(y)
{
cout << "A's ctor x = " << x << endl;
}
void print()
{
cout << "x = " << x << endl;
}
};
int main()
{
int i = 8;
A a(i);
a.print();
++i;
a.print();
}
The output is :
A's ctor x = 8
x = 8
x = 8
Why x isnt 9?
The issue is that you're binding a temporary (the constructor parameter y) to a reference. The lifetime of the temporary is restricted to the constructor, but your reference lives on, becoming a "dangling" reference. This is what a reasonable compiler has to say about the matter:
crap13.cpp:10:18: warning: binding reference member 'x' to stack allocated parameter 'y' [-Wdangling-field]
A(int y) : x(y)
You can "fix" this by making the constructor parameter a reference:
A(int& y) : x(y)
but you must ensure that whatever is passed as argument to the constructor outlives the object being constructed.
The problem is that you are passing int by value in your constructor, you should pass it by reference:
A(int& y) : x(y)
{
cout << "A's ctor x = " << x << endl;
}

What is the 'this' pointer?

I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario:
void do_something_to_a_foo(Foo *foo_instance);
void Foo::DoSomething()
{
do_something_to_a_foo(this);
}
I grabbed that from someone else's post on here.
What does this point to? I'm confused. The function has no input, so what is this doing?
this refers to the current object.
The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a non-static member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x.
The short answer is that this is a special keyword that identifies "this" object - the one on which you are currently operating. The slightly longer, more complex answer is this:
When you have a class, it can have member functions of two types: static and non-static. The non-static member functions must operate on a particular instance of the class, and they need to know where that instance is. To help them, the language defines an implicit variable (i.e. one that is declared automatically for you when it is needed without you having to do anything) which is called this and which will automatically be made to point to the particular instance of the class on which the member function is operating.
Consider this simple example:
#include <iostream>
class A
{
public:
A()
{
std::cout << "A::A: constructed at " << this << std::endl;
}
void SayHello()
{
std::cout << "Hi! I am the instance of A at " << this << std::endl;
}
};
int main(int, char **)
{
A a1;
A a2;
a1.SayHello();
a2.SayHello();
return 0;
}
When you compile and run this, observe that the value of this is different between a1 and a2.
Just some random facts about this to supplement the other answers:
class Foo {
public:
Foo * foo () { return this; }
const Foo * cfoo () const { return this; /* return foo(); is an error */ }
};
Foo x; // can call either x.foo() or x.cfoo()
const Foo y; // can only call x.cfoo()
When the object is const, the type of this becomes a pointer to const.
class Bar {
int x;
int y;
public:
Bar () : x(1), y(2) {}
void bar (int x = 3) {
int y = 4;
std::cout << "x: " << x << std::endl;
std::cout << "this->x: " << this->x << std::endl;
std::cout << "y: " << y << std::endl;
std::cout << "this->y: " << this->y << std::endl;
}
};
The this pointer can be used to access a member that was overshadowed by a function parameter or a local variable.
template <unsigned V>
class Foo {
unsigned v;
public:
Foo () : v(V) { std::cout << "<" << v << ">" << " this: " << this << std::endl; }
};
class Bar : public Foo<1>, public Foo<2>, public Foo<3> {
public:
Bar () { std::cout << "Bar this: " << this << std::endl; }
};
Multiple inheritance will cause the different parents to have different this values. Only the first inherited parent will have the same this value as the derived object.
this is a pointer to self (the object who invoked this).
Suppose you have an object of class Car named car which have a non static method getColor(), the call to this inside getColor() returns the adress of car (the instance of the class).
Static member functions does not have a this pointer(since they are not related to an instance).
this means the object of Foo on which DoSomething() is invoked. I explain it with example
void do_something_to_a_foo(Foo *foo_instance){
foo_instance->printFoo();
}
and our class
class Foo{
string fooName;
public:
Foo(string fName);
void printFoo();
void DoSomething();
};
Foo::Foo(string fName){
fooName = fName;
}
void Foo::printFoo(){
cout<<"the fooName is: "<<fooName<<endl;
}
void Foo::DoSomething(){
do_something_to_a_foo(this);
}
now we instantiate objects like
Foo fooObject("first);
f.DoSomething();//it will prints out first
similarly whatever the string will be passed to Foo constructor will be printed on calling DoSomething().Because for example in DoSomething() of above example "this" means fooObject and in do_something_to_a_foo() fooObject is passed by reference.
Acc. to Object Oriented Programming with c++ by Balaguruswamy
this is a pointer that points to the object for which this function was called. For example, the function call A.max() will set the pointer this to the address of the object. The pointer this is acts as an implicit argument to all the member functions.
You will find a great example of this pointer here. It also helped me to understand the concept.
http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
Nonstatic member functions such as Foo::DoSomething have an implicit parameter whose value is used for this. The standard specifies this in C++11 §5.2.2/4:
When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note ] If the function is a non-static member function, the this parameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4).
As a result, you need a Foo object to call DoSomething. That object simply becomes this.
The only difference (and it's trivial) between the this keyword and a normal, explicitly-declared const pointer parameter is that you cannot take the address of this.
It is a local pointer.It refers to the current object as local object

operator definition in base class

I have the following sample code. class bar is derived from the base class foo and allocates memory for ptr_x while read/write access are granted through the base class. This is a toy model for a large code in which read/write functions are the same for all different variants of an object but memory allocation slightly differs in different variants.
#include <iostream>
class foo{
protected:
int *ptr_x;
public:
foo(){
std::cout << " 1) Inside foo constructor: " << ptr_x << std::endl;
}
void read()
{
std::cout << " 2) Inside read function: " << ptr_x << std::endl;
std::cout << " 3) Inside read function: " << *ptr_x << std::endl;
}
void operator=(const int rhs)
{
std::cout << " 4) Inside operator= : " << ptr_x << std::endl;
*ptr_x = rhs;
}
};
class bar: public foo{
public:
bar(int a)
: foo()
{
std::cout << " 5) Inside bar constructor: " << ptr_x << std::endl;
ptr_x = new int;
std::cout << " 6) Inside bar constructor: " << ptr_x << std::endl;
*ptr_x = a;
}
~bar()
{
std::cout << " 7) Inside bar destructor: " << ptr_x << std::endl;
if (ptr_x != NULL) {delete ptr_x; ptr_x = NULL;}
}
};
int main (){
bar a(20);
a.read();
a = 40;
a.read();
return 0;
}
When I run the code, I get:
1) Inside foo constructor: 0
5) Inside bar constructor: 0
6) Inside bar constructor: 0x1d8f010
2) Inside read function: 0x1d8f010
3) Inside read function: 20
1) Inside foo constructor: 0x7f40c11e3b68
5) Inside bar constructor: 0x7f40c11e3b68
6) Inside bar constructor: 0x1d8f030
7) Inside bar destructor: 0x1d8f030
2) Inside read function: 0x1d8f030
3) Inside read function: 0
7) Inside bar destructor: 0x1d8f030
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000001d8f030 ***
I have the following questions: 1) Why does not code enter operator= in the base class? 2) Why is there a second call made to the constructor/destructor ? 3) why is there a double free problem?
what am I doing wrong here?
EDIT: Ok double free problem is obvious, but why is there two instances of same memory locations? This somehow has to do with operator= since when I comment it out everything is fine.
Thanks
Reasoning for the observed behavior:
The compiler uses the conversion constructor in derived class,
bar(int a)
for evaluating:
a = 40;
It takes in the integer 40 and creates a bar object using the conversion constructor and then assigns the created bar object to a using the implicit copy assignment operator(=) generated by the compiler for class bar.
This is the reason you see additional calls to bar constructor and that Base class overloaded = is never called. Also, the reason for double free lies in here, You have multiple bar objects which keep pointing to the dynamic memory allocated for ptr_x and when one of the object goes out of scope the destructor is called which deallocates the memory but leaves the other objects member pointer in a dangling state.
How to solve these problems:
You should mark the conversion constructor explicit if you don't want the compiler to use it for implicit conversions like this.
You should follow the Rule of Three for your class bar.
Caveat:
Note that the = operator in the base classes is always hidden by the implicitly generated = operator for the derived class.
For the first question you should have declared
bar (int a) as
explicit bar(int a).
this gives a proper compilation error that class bar should have = operator defined.

member variable

Can there be a member variable in a class which is not static but which needs to be defined
(as a static variable is defined for reserving memory)? If so, could I have an example? If not, then why are static members the only definable members?
BJARNE said if you want to use a member as an object ,you must define it.
But my program is showing error when i explicitly define a member variable:
class test{
int i;
int j;
//...
};
int test::i; // error: i is not static member.
In your example, declaring i and j in the class also defines them.
See this example:
#include <iostream>
class Foo
{
public:
int a; // Declares and defines a member variable
static int b; // Declare (only) a static member variable
};
int Foo::b; // Define the static member variable
You can now access a by declaring an object of type Foo, like this:
Foo my_foo;
my_foo.a = 10;
std::cout << "a = " << my_foo.a << '\n';
It's a little different for b: Because it is static it the same for all instance of Foo:
Foo my_first_foo;
Foo my_second_foo;
Foo::b = 10;
std::cout << "First b = " << my_first_foo.b << '\n';
std::cout << "Second b = " << my_second_foo.b << '\n';
std::cout << "Foo::b = " << Foo::b << '\n';
For the above all will print that b is 10.
in that case, you would use the initialization list of test's constructor to define the initial values for an instance like so:
class test {
int i;
int j;
//...
public:
test() : i(-12), j(4) {}
};
That definition reserves space for one integer, but there'll really be a separate integer for every instance of the class that you create. There could be a million of them, if your program creates that many instances of test.
Space for a non-static member is allocated at runtime each time an instance of the class is created. It's initialized by the class's constructor. For example, if you wanted the integer test::i to be initialized to the number 42 in each instance, you'd write the constructor like this:
test::test(): i(42) {
}
Then if you do
test foo;
test bar;
you get two objects, each of which contains an integer with the value 42. (The values can change after that, of course.)