What's a constructor real application in c++

I can initialize a member variable from a class for example with a constructor, of course but i can also do this by creating a variable of type class from which i could use it's members and initialize them by doing a function. So, i would like to know if the use of a constructor has something to do with reducing memory usage or real time enhancement that makes application more responsive.

Here i placed an example that i found on the internet. Trying to understand the real usage of a constructor in a c program as well in real life.

#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); private: double length; }; Line::Line(void) { cout << "Object is being created" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } int main( ) { Line line; line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }

-------------Problems Reply------------

One reason is that is reduces the scope for errors. Allowing an object to be constructed in an invalid/nonsensical state means it can be used in that state.

Line line;

// any read line.length is undefined behaviour
// What is the benefit of that?

line.setLength(6.0);

Constructors allow you to initialize instances in a valid and desired state, which means they can be used immediately without further manipulations.

Also, in regarding terminology, line.setLength(6.0) does not initialize the member, it modifies an already initialized one.

In real life, in larger nontrivial projects, you forget to call your own initializers, leaving the object in uninitialized state. But you can't forget to call a constructor.

A constructor provides a syntax that can guarantee that your object is completely initialized when it is created.

Bugs abound when you create an object that requires additional function calls before it's not in an uninitialized state.

There are reasons to favor a constructor over a method, and often, these reasons depend on the context. Let's first consider the most obvious reason to favor constructors: immutable objects. An object that's considered to be immutable will never change its state after its initial construction (where it's declared and constructed). Often, such immutable objects keep their member variables private and allow you to create other instances of them based on various functions (e.g., a string's substring routine).

On the other hand, objects which go through various state changes throughout their life (e.g., a GameBoard) may require client calls to modify their state. However, even these objects will be initialized somehow (e.g., think Chess, Checkers, Sudoko, etc...) and should require a basic constructor to ensure that they started from a "sane" initial state.

Methods can initialize objects, but only sometimes is this legal. For instance a member variable that is a reference must be initialized in the constructor list, variables that require parameters, variables that are const, etc...

From a performance perspective, I don't know how I would resolve this aspect of the question... but writing clean and clear code always makes other programmers reading your code efficient and, dare-i-say-it, happy! :-)

Category:c# Views:3 Time:2018-08-09

Related post

  • What is a practical, real world example of the Linked List? 2009-03-13

    I understand the definition of a Linked List, but how can it be represented and related to a common concept or item? For example, inheritance in OOP can be related to automobiles. All (most) automobiles in real life are the essentially same thing; an

  • What is the difference between application server and web server? 2009-06-01

    What is the difference between application server and web server? --------------Solutions------------- Most of the times these terms Web Server and Application server are used interchangeably. Following are some of the key differences in features of

  • What are greenfield and brownfield applications? 2009-09-22

    I read the following sentence in the Fluent NHibernate wiki: ...; however, for most greenfield applications (and quite a few brownfield ones too) auto mapping will be more than capable. What are greenfield and brownfield applications? --------------S

  • Where in real applications is a need for sorting numbers 2011-07-28

    Can anyone give some important/often used examples where there is a need for sorting (a large amount of )numbers in real applications Edit: Basically i thought of not so obvious places where sorting occurs but is not really evident to a user. So what

  • What are the benefits of applicative parsing over monadic parsing? 2011-10-22

    There seems to be a consensus that you should use Parsec as an applicative rather than a monad. What are the benefits of applicative parsing over monadic parsing? style performance abstraction Is monadic parsing out? --------------Solutions----------

  • What is a quality real world example of TDD in action? 2008-08-22

    What is a quality real world example of TDD in action? What small-to-medium open source projects in .net are out there that show off best practice in TDD and might work as a reference for doing TDD right? I am looking more for an example of a living

  • What's the difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException? 2010-01-06

    Alright, this is an easy one: What's the difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException? Do I need to handle both? Thanks! --------------Solutions------------- Application.ThreadException is specific to

  • What tools for server side application performance testing you suggest? 2010-03-11

    What tools for server side application performance testing you suggest? Have an application server and need to test it performance. Not sure issue is server side. Need to investigate. NB:Better to have convenient UI --------------Solutions-----------

  • What happens to my web application if JavaScript is disabled? 2010-03-22

    I'm learning jQuery and am about to write some pages using intensively that library. I just learned that some user disable JavaScript on their browser (I didn't even know that was possible and/or necessary). Now, here's my question: What happens to m

  • What are better Java web application frameworks (Suggestions please)? 2010-07-01

    I am new to Java Web Application. I am practicing with JSF2. Is it better to use any framework with JSF or just should I move with JSF? If it is better to use Framework, what you experienced guys suggest me? --------------Solutions------------- There

  • Where exactly the Singleton Pattern is used in real application? 2010-07-07

    I was just curious where exactly the singleton pattern is used... I know how the pattern works and where it can be used but i personally never used in any real application. Can some one give an example where it can be used.. I would really appreciate

  • In javascript, what is a constructor? And what isn't? 2010-10-28

    I'm using a plugin for jQuery. It works great in webkit, but when I try it in firefox I get the following firefox error: google.maps.Geocoder is not a constructor $('.to, .from').geo_autocomplete(new google.maps.Geocoder, { Here is all the jquery: $(

  • What does a constructor return? 2010-11-23

    My question is what does a constructor return? This question is not quite different from "What is the return type of a constructor?" I have read somewhere that a constructor returns a complete object implicitly (i.e implicit return type is the name o

  • What is happening when iphone application launched? 2011-02-08

    I'm doing a small research. I'm trying to find on the Internet but unfortunately can not. Can anyone explain or give a link to where it is explained what is happening when iPhone application is launched? I want to know consequence of actions and role

  • What's purpose of facebook application key 2011-02-11

    When you register a facebook application you get application id: 123455678 application key: hkjhkh3434hkklljk application secret: jkjljlj1233455jk For OAuth 2 only application id (a.k.a. client_id) and application secret (a.k.a. client_secret) are us

  • What is the difference between Application State and Application Session? 2011-03-16

    What is the difference between Application State and Application Session? --------------Solutions------------- A session is usually for a user and only lasts from when they login to when they logout (or get timed out). Application State has a much lo

  • Endian dependent code in real application? 2011-03-29

    I know the following C code is endian-dependent: short s_endian = 0x4142; char c_endian = *(char *)&s_endian; On a big-endian machine, c_endian will be 'A'(0x41); while on a little-endian machine, it will be 'B'(0x42). But this code seems kind of

  • What are good compression-oriented application programming interfaces (APIs)? 2011-07-14

    What are good compression-oriented application programming interfaces (APIs)? Do people still use the 1991 "data compression interface" draft standard, and the 1991 "Stream transformation algorithm interface" draft standard. (Both draft standards by

  • What can cause an IIS application to reset? 2011-08-08

    I am monitoring my site with a healthMonitoring section. I see a message... Event code: 1002 Event message: Application is shutting down. Reason: Hosting environment is shutting down. Event time: 8/8/2011 3:29:59 PM Event time (UTC): 8/8/2011 8:29:59

  • In context of WAS, what is the difference between application bounce and jvm bounce 2011-09-29

    In context of WAS, what is the difference between application bounce and jvm bounce. In case we only want to reload the data at server startup , whch one should we go for. --------------Solutions------------- The same application can be restarted mul

  • Is there any real application being self modifying code? 2011-10-03

    There are few examples on the web demonstrating how to write a self-modifying code. But they're just examples. I would like to know if there is any real application being self modifying code. Thanks! --------------Solutions------------- The first thi

  • what happens to the installed applications when the phone is replaced? 2012-01-08

    what happens to the installed applications when the phone is replaced? i would like to know what happens to both free and paid applications. --------------Solutions------------- Hi Duldul_874, Your applications are linked to your Windows Live id, so

  • Update issues. - When I open Internet Explorer it says that I need to choose what program to open the application with 2013-06-21

    Today I was told that I needed to update my windows software to keep it running. I executed the update and have had nothing but problems since. I am unable to access explorer 8 now, and every time I try to use explorer 9 it keeps saying that I need t

  • Just an public Question - Whats the best microsoft email application? 2013-08-21

    All this is, Is an general question. What would be the best application for emaling?, Microsft Outlook or Microsoft Live, or something else. Thanks for helping me out! Christopher Kelly Christopher Kelly - ChrisJets432 - ChrisJets Corporation CEO - C

  • Is there no information about what an update for an Application really updates? 2014-09-19

    Hello Microsoft When the Windows Phone tells me there is an update for an Application where can I find information (ON THE PHONE!!!) about what the update really concerns. What is fixed and what it does to the Application?! The same problem happened

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.114 (s). 12 q(s)