473,388 Members | 1,215 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Constructor function

Hello All,

I am little confused about the constructor function. Say I have a class
like the following

class test{
int a;
public:

test(){}
test(int a){
this->a = a;
}
test(test &b){
this->a = b.a
}
void printVal(){
cout<<a<<endl;
}

}

now in my main function I have the following

(test(2)).printVal();

this works. It creates an unnamed object. (Can I call this unnamed
object?)

The following is true also

test b;
b = test(2);

here, two objects are being created. The "b" is a copy of unnamed
object created by the constructor "test(2)".

Does it mean that the constructor is returning an object of test?
Also what happens in the following case? Say I have function in the
file scope like this

void myFunc(test a){

a.printVal();

}

what happens when I call this from main like this:

myFunc(test(2));

here, the constructor creates an unnamed object, then myFunc gets that
object. But how? I tested this, and I found out that neither the copy
constructor nor the assignment operator(=) is being called in this
case!

Help me in my concept of theses!

thanks a lot

Jul 23 '05 #1
5 2849
wrote in news:11**********************@z14g2000cwz.googlegr oups.com in
comp.lang.c++:
Hello All,

I am little confused about the constructor function. Say I have a class
like the following

class test{
int a;
public:

test(){}
test(int a){
this->a = a;
}
test(test &b){
this->a = b.a
}
void printVal(){
cout<<a<<endl;
}

}

now in my main function I have the following

(test(2)).printVal();

this works. It creates an unnamed object. (Can I call this unnamed
object?)

(Yes, its as good a name as any other, but "a temporary" might
be better, we don't need to say unnamed-temporary as temporaries
are always unnamed).
The following is true also

test b;
b = test(2);

here, two objects are being created. The "b" is a copy of unnamed
object created by the constructor "test(2)".

Does it mean that the constructor is returning an object of test?

No, well not really ;-(, the compiler creates storage for an temporary
and passes that storage to the constructor (the 'this' variable points
to it).

Also what happens in the following case? Say I have function in the
file scope like this

void myFunc(test a){

a.printVal();

}

what happens when I call this from main like this:

myFunc(test(2));

here, the constructor creates an unnamed object, then myFunc gets that
object. But how? I tested this, and I found out that neither the copy
constructor nor the assignment operator(=) is being called in this
case!


The copy constructor is used (but there is a twist, as you've dicovered).

The copy construction can be elided (by passed) when the compiler can,
as in this case, construct the object directly in to the target variable.

The compiler is allowed to do this even if the copy constructor has side
effects (such as: std::cout << "In copy constructor\n";).

So in the above exmple the compiler will create storage for the paramiter
'a' of myFunc, and then call the constructor (test::test( int )) to
construct it in-place, eliding (by passing) the copy constructor.

HTH.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #2
bipod.rafique wrote:
test(int a){
this->a = a;
Greetings, and congrats from escaping Java. You will find well-written C++
code to be safer, more elegant, and much more productive...

In the above case, either name a different or replace this->a with m_a.
That's a common "wart" to make members look different from locals.
test b;
b = test(2);

here, two objects are being created. The "b" is a copy of unnamed
object created by the constructor "test(2)".

Does it mean that the constructor is returning an object of test?
A constructor is not a function - it's a special block of code invoked when
you speak the name of its class. The above works as if 'b' fully
constructed, then a temporary fully constructed, then the assignment
operator = copied the temporary into 'b'.

Certain minor optimizations happen, and some of those are permitted to elide
extra constructions and copies, but you should not write code that does too
much in constructors so you shouldn't worry about those.
void myFunc(test a){

a.printVal();

}

what happens when I call this from main like this:

myFunc(test(2));
That's redundant. Consider test a = 2. You get the same effect with
myFunc(2).
here, the constructor creates an unnamed object, then myFunc gets that
object. But how? I tested this, and I found out that neither the copy
constructor nor the assignment operator(=) is being called in this
case!


Because of the minor optimizations I warned of - specifically the return
value construction optimization. Someone here will remember its proper name.

--
Phlip
http://www.c2.com/cgi/wiki?ZeekLand
Jul 23 '05 #3
Phlip wrote:
A constructor is not a function - it's a special block of code invoked when
you speak the name of its class.


It is a function. It comes under the group of things called special
member functions. However, it does not participate in name resolution
and hence can't be called. Other than that, it follows the same
rules that other non-static member functions do.
Jul 24 '05 #4

<bi***********@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Hello All,

I am little confused about the constructor function. Say I have a class
like the following

class test{
int a;
public:

test(){}
test(int a){
this->a = a;
}
test(test &b){
this->a = b.a
}
void printVal(){
cout<<a<<endl;
}

} semicolon required here

First off, simplify your life with proper nomenclature and learn about the
constructor's initialization list. Note also that the copy constructor uses
a constant reference as an arguement.

#include <iostream>

class Test
{
int m_a;
public:
Test() : m_a(0) { std::cout << "Test()\n"; } // default ctor
Test(int a) : m_a(a) { std::cout << "Test(int)\n"; } // argument ctor
// copy ctor
Test(const Test& r_copy)
{
std::cout << "Test copy ctor\n";
m_a = r_copy.m_a;
}

// Member Function
void printVal() const
{
std::cout << "m_a = " << m_a << std::endl;
}
}; // class Test

int main()
{
Test test(2);
test.printVal();

Test test1;
test1 = Test(4);
test1.printVal();

return 0;
}

/*
Test(int)
m_a = 2
Test()
Test(int)
m_a = 4
*/

now in my main function I have the following

(test(2)).printVal();

this works. It creates an unnamed object. (Can I call this unnamed
object?)
Yes, its an anonymous object. We call this type of object a temporary.

The following is true also

test b;
b = test(2);

here, two objects are being created. The "b" is a copy of unnamed
object created by the constructor "test(2)".

Does it mean that the constructor is returning an object of test?
No, there is no need to here. The compiler recognizes that generating the
temporary and then assigning its contents to b is overkill. So...
Test b = Test(2);
is equivalent to...
Test b(2);


Also what happens in the following case? Say I have function in the
file scope like this

void myFunc(test a){

a.printVal();

}

what happens when I call this from main like this:

myFunc(test(2));

here, the constructor creates an unnamed object, then myFunc gets that
object. But how? I tested this, and I found out that neither the copy
constructor nor the assignment operator(=) is being called in this
case!
Rob's explanation is better than i could have provided.

Help me in my concept of theses!

thanks a lot


Jul 24 '05 #5
Peter Julian wrote in news:HG********************@news20.bellglobal.com in
comp.lang.c++:
Note also that the copy constructor uses
a constant reference as an arguement.


The compiler generate one does.

However we can can use any signature we want as long as it takes
a (possibly qualified) reference to the class type as its first
argument and any subsiquent arguments have default values.

We can even have all 4 and have overload resolution:

#include <iostream>
using namespace std;

struct A
{
A() {}
A( A &, int value = 0 )
{
std::cout << "A::A( A &, " << value << " )\n";
}
A( A const & ) { std::cout << "A::A( A const & )\n"; }
A( A volatile & ) { std::cout << "A::A( A volatile & )\n"; }
A( A const volatile & )
{
std::cout << "A::A( A const volatile & )\n";
}
};

int main()
{
A a;
A const ac( a );
A volatile av( ac );
A const volatile acv( av );
A another( acv );
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 24 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jun | last post by:
I have following script <script> var Animal = function(name){ this.name = name; } Animal.prototype.eat = function (food) {
34
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is...
2
by: vakap | last post by:
function show() { var s = '' ; for (var i = 0; i<arguments.length; s += '\n'+arguments) ; typeof(window) != 'undefined' ? window.alert(s) : WScript.Echo(s) ; } function f(){}...
10
by: John Brock | last post by:
I have a base class with several derived classes (I'm writing in VB.NET). I want each derived class to have a unique class ID (a String), and I want the derived classes to inherit from the base...
19
by: Martin Oddman | last post by:
Hi, I have a compiling problem. Please take a look at the code below. I have an application that is built upon three tiers: one data tier (Foo.DataManager), one business tier (Foo.Kernel) and...
16
by: plmanikandan | last post by:
Hi, I have doubts reg virtual constructor what is virtual constructor? Is c++ supports virtual constructor? Can anybody explain me about virtual constructor? Regards, Mani
26
by: Patient Guy | last post by:
The code below shows the familiar way of restricting a function to be a method of a constructed object: function aConstructor(arg) { if (typeof(arg) == "undefined") return (null);...
74
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
9
by: Morten Lemvigh | last post by:
Is it possible to pass a pointer to a constructor or a class definition as argument to a function? Maybe in a way similar to passing function pointers...? The function should construct a number...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.