How are the Constructor and Destructors called - c++

#include<iostream>
class Example{
int i=0,j=0;
public:
Example(){
std::cout<<"Default Constructor is called "<<j++<<std::endl;
}
~Example(){
std::cout<<"Destructor is Called "<<i++<<std::endl;
}
void display(){
std::cout<<"Display method called "<<std::endl;
}
};
void function(){
Example e;
e.display();
}
int main(){
function();
Example e1;
}
I'm trying to see how the constructor and destructor are called for two objects of the same class
The output I'm getting is
Default Constructor is called 0
Display method is called
Destructor is called 0
Default Constructor is called 0
Destructor is called 0
Why is my i and j variable not getting incremented

Your i and j variables are incremented, but the results are not printed.
You used postfix increment operator, so it is evaluated to the value before incrementing.
As you say, there are two objects, and they have independend member variables i and j because they are not static.

Since both the objects are independent of each other so incremented values will not affect another object. They are incrementing , if you want to see the incremented value then you can try pre-increment by using ++i or ++j instead of i++ or j++.
To know more you comment.

You have 2 different objects of class Example namely e and e1. Where e belongs to your defined function function, and e1 belongs to the main function.
So when you execute your program, object e only gets called once and the values of i and j get incremented for that object. But then you use another object e1, for which their values different than previously called object e. That's why values of i and j are different for different objects. Every time you create a new object, they get initialized to 0 for that object.
Now, what you have to do to make these values same for all objects is to make those variables static. Static will make variables accessible to all objects you create of same class with unchanged value and they don't get initialize every time you create a new object.
Here is how you can do it:
static int i,j;
But make sure you don't initialize static variables inside class. Otherwise program will throw an error. So, to initialize your static variables to 0, access them outside of class and set them to whatever value you wish to initialize them with. Like following:
int Example::i = 0;
int Example::j = 0;
That's it. Now you can achieve what you were looking for.
So now your code must look something like this:
class Example{
static int i,j;
public:
Example(){
std::cout<<"Default Constructor is called "<<j++<<std::endl;
}
~Example(){
std::cout<<"Destructor is Called "<<i++<<std::endl;
}
void display(){
std::cout<<"Display method called "<<std::endl;
}
};
int Example::i = 0;
int Example::j = 0;
void function(){
Example e;
e.display();
}
int main(){
function();
Example e1;
}

Change has been made. Please run this again
#include<iostream>
class Example{
static int i,j; //Changed
public:
Example(){
std::cout<<"Default Constructor is called "<<j++<<std::endl;
}
~Example(){
std::cout<<"Destructor is Called "<<i++<<std::endl;
}
void display(){
std::cout<<"Display method called "<<std::endl;
}
};
int Example::i = 0; //initializing i and j like this outside the class
int Example::j = 0; //Added
void function(){
Example e;
e.display();
}
int main(){
function();
Example e1;
}

Related

Passing Array of objects to same class C++

Question : Declare a class named ‘StudentRec’ with three private members: ‘enrolNo’ of type int, ‘CGPA’ of type float and ‘branch’ of type string. Declare an array of objects named ‘Student’ of size 5 of class ‘StudentRec’. Write public member functions: (i) void sort (StudentRec Student[], int N ) to sort the data in ascending order with respect to ‘CGPA’ and (ii) void print (StudentRec Student[], int N ) to display the sorted and unsorted students’ records. Write main to test these member functions.
Doubt : The sorting part I will do later. My doubt is if in the below code(2nd last line ) Student[5].print(Student, N ); is correct way to call the function print? How else can this function be called via array of objects Also Student[0].print(Student, N ) gives correct output. Why ?
#include<iostream>
#include<cstring>
using namespace std;
class StudentRec
{
private:
int enrolNo;
float CGPA;
string branch;
public:
void assign()
{
cin>>enrolNo>>CGPA>>branch;
}
void sort (StudentRec Student[], int N );
void print(StudentRec Student[], int N )
{
int i;
for(i=0; i<5; i++)
{
cout<<"Student"<<" "<<i<<" " ;
cout<<Student[i].enrolNo<<" "<<Student[i].CGPA<<" "<<Student[i].branch<<endl;
}
}
};
int main()
{
StudentRec Student[5];
int i,N=5;
for(i=0; i<5; i++)
Student[i].assign();
Student[5].print(Student, N );
return 0;
}
As has been pointed out, Student[5].print(Student, N ); invokes undefined behavior as there is no Student[5]. However, your implementation of print doesn't actually use the object it is invoked on, so this is probably why this works in practice.
To give your program a somewhat reasonable design while keeping as close to the assignment as possible, you can declare the functions static:
static void print(StudentRec Student[], int N );
This means that, while the functions are declared inside the class and have access to private members of objects of the class, they don't rely on any concrete object to be invoked. You can then use them like this:
StudentRec::print(Student, N);
On a side note, your implementation of print doesn't actually use the parameter N.

How to create objects outside functions with polymorphism?

I want to use polymorphism and create objects outside of main or any other function so that the functions are independent of the type of the objects I have. My code is as follows:
The main class:
class load{ //Main class
protected:
static load **L;
static int n, n1;
public:
load(){};
virtual float getpower()=0;
static int getn();
static load ** getL();
};
load **load::L;
int load::n;
int load::n1;
int load::getn(){
return n;
}
load** load::getL(){
return L;
}
The child class:
class load1:public load{
private:
float power;
public:
load1();
load1(int s);
void createUnits1();
float getpower();
}l1(0); //Object creation
load1::load1(int s){
createUnits1();
}
void load1::createUnits1(){
cout<<"Give the number of type 1 objects: "<<endl;
cin>>n1;
for (int i=0;i<n1;i++){
load1 temp; //Run default constructor
}
}
load1::load1(){
cout<<"Give the power of the device: "<<endl;
cin>>power;
n++;
if (n==1){
L=(load **)malloc(n*sizeof(load *));
}
else {
L=(load **)realloc(L,n*sizeof(load *));
}
L[n-1]=this;
}
float load1::getpower(){
return power;
}
The function of calculation:
float get_total_P(load **l, int num){
float tot_power=0;
for(int i=0;i<num;i++){
tot_power+=l[i]->getpower();
}
return tot_power;
}
My main function:
int main() {
load **l;
int num;
num=load::getn();
l=load::getL();
float total_P=get_total_P(l, num);
cout<<total_P;
return 0;
}
The upper code produces a segmentation fault but I can't see the reason why. The segmentation fault is on the line
tot_power+=l[i]->getpower();
So I guess my way of creating objects is wrong. Is there a better way to do this?
The reason for your segfault, is that l doesn't point to anything valid !
In main() you initialise l with load::getL(). But this function only returns the load::L which has the same type and was defined as static in your load class but was never initialized.
You have coded in your derived class load1 some initialisation code for L, but it is never invoqued in main().
Your code has also some severe design issues:
It's not advised to use malloc() and realloc() in C++ code. If you create an object in C++ use new. If you want some dynamic array, use vectors.
You could get L and hence l initialized if you'd create some load1 objects before calling getL(). But due to your realloc, l would then risk to point to an obsolete thus invalid address, if you would create any other load1 object before calling get_total().
It's bad practice and terrible design to request user input in a constructor. The constructor is meant to cosntruct an object with the parameters you give him when you call him. Imagine the user would give an invalid parameter ? The user would be asked for input whenever a load1 object is constucted. Even for temporary variables, not even speaking from the effect when you'd write load1 a[10];

C++ static object Class function

Some code:
Please see the class myClass below . it has a constructor and a public recursive function find. Please see code:
#include <iostream>
using namespace std;
class myClass{
public:
myClass() {
//do stuff
}
int find(int i) {
static int j = 10;
if (i > 15)
return i;
j = j + 1;
return i * find(j + 1);
}
};
int main()
{
myClass mC1 ,mC2;
cout<< " 1.... return value = "<< mC1.find(10);
cout<< " \n 2... return value = "<< mC2.find(10);
return 1;
}
output:
1.... return value = 5241600
2.... return value = 170
The above progemn has a class myclass having a function find .. "find" function has a variabe . This is static which is required as i wanted a recursive function . Problem is static varible has life of a program & binded to class .
However I want the static to be object specfic and not class scope . I wanted both the function calls to return me same value .
Simply put , how to make a static varable in a class function , to be per object and not for whole class...
Do you need a member variable?
Hope the following code helps.
Best regards
Sam
class myClass{
public
myClass() {
m_j = 10;
}
private:
int m_j; // private member variable for find algorithm;
int find(int i) {
if(i>15)
return i;
m_j= m_j+1;
return i * find(m_j+1);
}
};
If you want a per object variable you need to make it a member of the respective object. There is no way to declare a variable inside a function to be specific to objects. The way you use use static member could be changed to be non-static anyway, i.e., you would get the necessary context: Make the function non-static and store the data in the object as needed.
That said, just because a function is recursive doesn't mean that it needs any sort of static context. Normally, all the necessary context is passed to the recursive function as parameters in which case the system keeps the necessary state on the stack. Since the stack is relatively limited in size you want to make sure that you don't need too much context in recursive functions with deep call stack.
Since you probably don't want to require the user to pass in some internal context, the find() function in the the interface would probably just delegate to the recursive function providing the necessary context. For example:
int find(int j, int i) {
if (15 < i) {
return i;
}
++j;
return i * find(j, j + 1);
}
int find(int value) {
return find(10, value);
}
(I'm not sure if I got the desired logic right because I didn't quite get what the function is meant to do...).

C++ Logic Bug: Trying to Generate Unique ObjectIDs for all Instances Created, Counter Registering Incorrectly

I am working on a project that must allow all instances created to have a unique objID. All classes inherit from one base class that has a static variable that increments whenever any of the concrete classes constructor(s) are called. The counter keeps running until program is quit.
The problem I am having is when I use an array (any C++ containers), the objID registers more then one increment.
For example:
In my main() I created a vector<ConcreteClassA> cc; and did a push_back(...) twice.
My Output was:
objID = 5, and count = 2
Expected Result:
objID = 2, and count = 2
I am not sure why my ObjID is registering more then once for each push_back(...). I have gone through and checked all locations to make sure my assign() is only called in constructors of my concrete classes.
Please advise.
//===========================================================================
//Main.cpp
#include "ConcreteClassA.h";
#include <iostream>
#include <vector>
#using namespace std;
int main()
{
vector<ConcreteClassA> c1;
cc.push_back( ConcreteClassA() );
cc.push_back( ConcreteClassA() );
return 0;
}
//objID is off for some reason....
//Expected Results: count = 2, objID = 2
//Output: count = 2, objID = 5
//===========================================================================
//IBase.h file
private:
static int objID; //used to assign unique IDs
static int count; //track how many stances of all objs are active
protected:
const int assignID(); //return a new ID
void decrementCount(); //decrement count, when an obj is removed
//===========================================================================
//IBase.cpp
int IBase::objID = 0;
int IBase::count= 0;
const int IBase::assignID()
{
++ this->count;
++ this->objID;
return ( this->objID );
}
void IBase::decrementCount()
{
-- this->count;
}
//===========================================================================
ConcreteClassA.h
ConcreteClassA(); //default constructor
ConcreteClassA(...); //couple overloaded constructors
~ConcreteClassA(); //destructor
ConcreteClassA( const ConcreteClassA &cc ); //copy constructor
ConcreteClassA& operator=(const ConcreteClassA &cc); //assignment operator
//more methods....
//===========================================================================
ConcreteClassA.cpp
//destructor makes sure instances tracking counter is decremented
ConcreteClassA::~ConcreteClassA()
{
this->decrementCount();
}
//only constructors and assignemnt operators call assign() method
ConcreteClassA::ConcreteClassA()
{
//some other initialization...
this->assignID();
}
//All other methods implementation left out for sensitivity of real estate...
You have to account for copies of the object. In C++ vector<T>::push_back() puts a copy of the object into the vector. The temp instances that you created in the function call are getting destroyed. That is why the "created" count is higher that the "active" count.
If you really want to be stingy about creating instances of the object, maybe you should store pointers in the vector. That way you have to explicitly create and destroy them.
Here's a nice post on something like that:
https://stackoverflow.com/a/1361227/2174
void IBase::decrementCount()
{
-- this->count;
}
Woah, I haven't checked the operator precedence there, but I'd write
void IBase::decrementCount()
{
-- (this->count);
}
without even thinking twice. (A good guideline is, that if you can have a doubt or would want to check, you should write it more clearly).
And, yes, that should just be
void IBase::decrementCount()
{
--count;
}

Is it possible to pass a variable out of a class without creating a new object in C++

I have a variable, which is a member of one of my classes, that another is in need of, but I'm not sure how to effectively pass the value between them without using a global variable, which is something I'd like to avoid if at all possible. I know I could create an object, but that would invoke the constructor of the originating class which would execute a number of functions and write the needless results to memory, which would be wasteful of system resources.
Is there an easy way to pass this value between the two functions?
Update: The class that is in need of the variable, called no_of_existing_devices. The purpose of class Initialise is to open up a file and count the number of lines of test it contains, and place that number in the variable int no_of_existing_devices, which is then used by the Device::Device() to create an object for each
class Device
{
public:
void view_attribute_list();
void set_attribute();
Device();
};
Device::Device()
{
for (int count = 0; count < no_of_existing_devices; count ++)
{
// Create an object for each iteration, up to a maximum of no_of_existing_devices
}
}
The class of which this variable is a member
class Initialise
{
public:
int no_of_existing_devices;
bool initialisation;
string existing_device_list[100];
void initialise_existing_devices();
Initialise();
};
Initialise::Initialise()
{
no_of_existing_devices = 0;
}
void Initialise::initialise_existing_devices()
{
string line;
ifstream DeviceList;
DeviceList.open("devices/device_list");
while (true)
{
getline(DeviceList, line, '\n');
if (DeviceList.eof())
{
break;
}
++ no_of_existing_devices;
}
DeviceList.close();
DeviceList.open("devices/device_list");
for (int i = 0; i < no_of_existing_devices; i ++)
{
getline(DeviceList, line, '\n');
existing_device_list[i] = line;
}
Device existing_devices[no_of_existing_devices];
!initialisation; // Existing devices are now initialised
}
Okay, from what I understand:
You don't want to have a global
You don't want to have a static
You don't want to introduce a dependency between Device and Initialise
There is one other option, assuming something owns Device and Initialise, move the no_of_existing_devices up to there, then construct both Device and Initialise with a reference to this variable...
In a similar circumstance I was just passing the pointer to the member --- I had to invoke a member function then, so it was a pointer to the member function, http://www.parashift.com/c++-faq-lite/pointers-to-members.html
It's a bit messy, but it works :-).
If the variable in the originating class can hold a value without an instance of the class I would assume that the variable is static. If not create a public static member of the class. And use it in the target class.
Something like:
// .h file
class A
{
public:
static int a;
}
// .cpp file
int A::a = 123;
// .cpp file of class B
void B::foo()
{
cout << A::a;
}
If it is a class attribute (internal variable), then you can obtain a reference through a get method. Otherwise, you can use the friend keyword on the class you want to access the attribtue from the other For example, if you declare friend class B; on class A, the attributes of the class B will be accessible on the class A.
I suggest you use the first method in order to maintain your code OO pure ;)
Edit: of course, if you access through a reference there are no resources wasted :)
Edit 2: use a static method on Initialise class that returns the no_of_existing_devices and call Initialise::NoOfExistingDevices() on the Device class. If you want to resources use a pointer like this:
public static int* Initialise::NoOfExistingDevices() {
return &no_of_existing_devices;
}
By the way, I advise you to turn the variable private.