LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-27-2010, 08:30 AM   #1
thelink123
Member
 
Registered: Aug 2008
Location: India, Kerala
Distribution: openSUSE 11
Posts: 46

Rep: Reputation: 15
Wink C++ : Constructor in 'Private' section of class


Kindly take a look at the following code

Code:
 #include <iostream>

 using namespace std;

 class private_cons
 {

 private:

    int i;

    private_cons(int num)
    {
       i = num;
    }

 public:

    private_cons()
    {
       private_cons obj1(30);

    }

    int get_i()
    {

       return i;

    }

 };

 int main ()
 {
    private_cons obj;

    cout << "Value = " << obj.get_i();

    return 0;

 }
I expected the output to be

Quote:
Value = 30
Instead i got some big value like

Quote:
Value = 1629727663
Kindly let me know the reason for this.

Thanks
-Nitin

Last edited by thelink123; 08-27-2010 at 08:32 AM.
 
Old 08-27-2010, 09:13 AM   #2
crabboy
Senior Member
 
Registered: Feb 2001
Location: Atlanta, GA
Distribution: Slackware
Posts: 1,821

Rep: Reputation: 121Reputation: 121
The public constructor private_cons is creating his own object, obj1 which assigns the value of 30 to i to that object. Once the constructor exists, that object goes out of scope and your 30 is gone. The i for obj is never assigned.

Add this line to the end of your public constructor and maybe it will make sense to you.

Code:
i = obj1.get_i();
 
1 members found this post helpful.
Old 08-27-2010, 09:58 AM   #3
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by thelink123 View Post
Code:
    private_cons()
    {
       private_cons obj1(30);

    }
Do you have previous experience in some language, such as Java, that lets a constructor call another constructor for the same object?

C++ doesn't give you any way to do that. That fact is often inconvenient when writing C++ code.

As crabboy explained, what you actually did was have a constructor call a different constructor of the same class but for a different object.

One common, but imperfect, work around for not being able to call another constructor for the same object is to move all the actual construction to init methods:
Code:
#include <iostream>

 using namespace std;

 class private_cons
 {

 private:

    int i;

    private_cons(int num)
    {
       init(num);
    }

    void init(int num)
    {
       i = num;
    }
 public:

    private_cons()
    {
       init(30);

    }

    int get_i()
    {

       return i;

    }

 };

 int main ()
 {
    private_cons obj;

    cout << "Value = " << obj.get_i();

    return 0;

 }
Another method, that is often better, is to move the data members and true constructors of your class into a base class:

Code:
#include <iostream>

 using namespace std;

 class base_class_for_private_cons
 {
 protected:
    int i;
    base_class_for_private_cons(int num) :
      i(num)
    {}
 };
 class private_cons : private base_class_for_private_cons
 {

 private:

    private_cons(int num) :
      base_class_for_private_cons(num)
    {}

 public:

    private_cons() :
      base_class_for_private_cons(30)
    {}

    int get_i()
    {

       return i;

    }

 };

 int main ()
 {
    private_cons obj;

    cout << "Value = " << obj.get_i();

    return 0;

 }
Depending on details of what else you want to do, the part I put in red is probably not needed.

Last edited by johnsfine; 08-27-2010 at 10:08 AM.
 
Old 08-27-2010, 10:27 AM   #4
David1357
Senior Member
 
Registered: Aug 2007
Location: South Carolina, U.S.A.
Distribution: Ubuntu, Fedora Core, Red Hat, SUSE, Gentoo, DSL, coLinux, uClinux
Posts: 1,302
Blog Entries: 1

Rep: Reputation: 107Reputation: 107
Try
Code:
#include <iostream>

using namespace std;

class private_cons
{
private:
    int i;
    private_cons(int num) : i(num) { }

public:
    private_cons() { *this = private_cons(30); }

    int get_i() { return i; }
};

int main ()
{
    private_cons obj;

    cout << "Value = " << obj.get_i() << endl;

    return 0;
}
 
Old 08-27-2010, 12:05 PM   #5
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by David1357 View Post
Try
Code:
    private_cons() { *this = private_cons(30); }
No. Do not do that!

You are violating basic concepts of the language. You are using the desired constructor on a different instance of the object (as the OP did) and that would be OK, but

You are using operator=() to copy to an incompletely constructed left hand side. That is wrong.

operator=() should be used only to replace contents of a fully constructed left hand side. It should not be used with a partially constructed left hand side.

We are looking at an example that is both trivial and POD. So you could do many things that are generally wrong C++ and they won't malfunction. But you should almost always code C++ as if you are working on a real project that will grow and evolve. Wrong code that happens to be safe because something else is unusually simple represents a land mine that is likely to blow up when unrelated reasonable looking changes are made.

Also, remember the OP didn't post the code He/She actually wants to use. We constantly tell people to cut their code down to a full compilable example that still contains the problem. That almost always involves keeping just the problem itself while discarding the reason it was coded that way. So when we make a suggestion for fixing the problem we should try not to assume the code was written that way for no good purpose.

If there is a good reason to have a private constructor and to want a public constructor to use the private constructor (rather than to simply initialize the members itself) then there is almost certainly also a reason that operator=() into a half constructed left hand side will malfunction.
 
Old 08-27-2010, 12:13 PM   #6
David1357
Senior Member
 
Registered: Aug 2007
Location: South Carolina, U.S.A.
Distribution: Ubuntu, Fedora Core, Red Hat, SUSE, Gentoo, DSL, coLinux, uClinux
Posts: 1,302
Blog Entries: 1

Rep: Reputation: 107Reputation: 107
Quote:
Originally Posted by johnsfine View Post
You are using operator=() to copy to an incompletely constructed left hand side.
How is it incompletely constructed? Please quote chapter and verse when you make such a statement.

If there were any other members that needed to be initialized specifically, they could be added to the private constructor. As long as the right hand side is completely constructed, and all you want is a copy of the right hand side, I fail to see how the code is "wrong".
 
Old 08-27-2010, 12:49 PM   #7
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
johnsfine is correct.

And, as he also pointed out, the bug is *especially* pernicious because most of the time (including in "toy" examples like this), it will *seem* to work.

IMHO .. PSM
 
Old 08-27-2010, 01:12 PM   #8
David1357
Senior Member
 
Registered: Aug 2007
Location: South Carolina, U.S.A.
Distribution: Ubuntu, Fedora Core, Red Hat, SUSE, Gentoo, DSL, coLinux, uClinux
Posts: 1,302
Blog Entries: 1

Rep: Reputation: 107Reputation: 107
Quote:
Originally Posted by paulsm4 View Post
johnsfine is correct.
Please provide a reference.
 
Old 08-30-2010, 12:48 AM   #9
thelink123
Member
 
Registered: Aug 2008
Location: India, Kerala
Distribution: openSUSE 11
Posts: 46

Original Poster
Rep: Reputation: 15
Thumbs up

Thank you all ... Very informative explanations by all LQ members who have contributed to this thread

-thelink123
 
  


Reply

Tags
c++, constructor



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
C++, How to initialize nested class constructor?? jayasekar Programming 4 04-02-2010 12:18 PM
Does derivated class inherit base class destructor (constructor)? kornerr Programming 2 08-23-2006 08:05 AM
fopen fclose in class constructor bedoni Programming 9 03-26-2006 10:25 AM
Undefined references to vtable in class constructor? RavenOfOdin Programming 2 03-01-2006 05:46 PM
Class constructor not being called ChimpFace9000 Programming 1 06-03-2002 08:54 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:15 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration