Displaying object name inside destructor - c++

Inside FileTwo.h
#include"iostream"
using namespace std ;
class FileTwo{
public:
FileTwo(){
cout<<"constructor for";//Here want to show the object for which the constructor has been called
}
~Filetwo(){
cout<<"Destructor for ";//Here want to show the object for which the destructor has been called
};
Inside main.cpp
#include"Filetwo.h"
int main(){
FileTwo two ;
return 0;
}
I know this sample program is very small , so we can able to find out the object for which the constructor and destructor has been called . But for big project is there any way to know the object name ? Thanks in advance .

It is possible. If your compile supports __PRETTY_FUNCTION__ or __func__ (see this), then you can do this:
#include <iostream>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
Note that I've also printed to cerr to ensure that this output gets flushed immediately and isn't lost if the program crashes. Also, since each object has a unique *this pointer, we can use that to see when particular objects are being made or getting killed.
The output for the above program on my computer is:
constructor for FileTwo::FileTwo() at 0x7fff641cde40
Destructor for FileTwo::FileTwo() at 0x7fff641cde40
Note that __func__ is a C99 standard identifier. C++0x adds support in the form of an "implementation-defined string".
__FUNCTION__ is a pre-standard extension supported by some compilers, including Visual C++ (see documentation) and gcc (see documentation).
__PRETTY_FUNCION__ is a gcc extension, which does the same sort of stuff, but prettier.
This question has more information on these identifiers.
Depending on your compiler, this may return the name of the class, though it may be a little mangled.
#include <iostream>
#include <typeinfo>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
If you are trying to get the name of the variable to which the class is instantiated (two in your case), then there is not, to my knowledge, a way to do this. The following will emulate it:
#include <iostream>
#include <string>
using namespace std;
class FileTwo{
public:
FileTwo(const std::string &myName) : myName(myName) {
cerr<<"constructor for "<< myName <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< myName <<" at "<<&(*this)<<endl;
}
private:
std::string myName;
};
int main(){
FileTwo two("two");
return 0;
}

Unless you name the object, it is not possible. Something like this :
#include <iostream>
#include <string>
using namespace std;
class FileTwo {
public:
FileTwo(const std::string &myName) : name(myName){
cout<<"constructor for" << name;//Here want to show the object for which the constructor has been called
}
~Filetwo(){
cout<<"Destructor for " << name;//Here want to show the object for which the destructor has been called
}
private:
std::string name;
};
and then change the main into :
#include"Filetwo.h"
int main(){
FileTwo two("two 11");
}

It is not possible to name the object,all what you can do is making a private variable to hold the name.
using namespace std;
class myClass
{
private:
string className;
public:
~myClass()
{
cout<<this->className;
}
};
you can create setters and getters for you variable.
void SetName(string name)
{
this->className = name;
}
string GetName()
{
return this->className;
}

Related

How to get class name at compile time? [duplicate]

This question already has answers here:
How can I get the class name from a C++ object?
(9 answers)
Closed 8 months ago.
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
class People{
public:
string name;
int age;
bool educated;
People(){
cout << [name] << "class people is initialised" << endl;
}
~People(){
cout << [name] << "class people is destroyed" << endl;
}
private:
double worth;
};
int main(){
People Joe;
}
how do i display that class name in the constructor and destructor?
I saw another method was calling the function specifically in main() however that is not what i want. I want to try to display the class name upon its creation and destruction
Welcome to stackoverflow and C++!
I tool the liberty of fixing some smaller issues with the code:
<cmath> is the proper C++ header, use that instead of <math.h> (the C header. C and C++ are different).
Do not build an early habit of using namespace std. Yes, it seems convenient, but read here why you should not do it.
Using std::endl will likely drop your performance. Read here about the differences. using \n works just as good, is cross-platform-compatible and even less to type.
Does this achieve what you want?
#include <cmath>
#include <iostream>
#include <string>
class People{
public:
std::string name;
int age;
bool educated;
People(){
std::cout << typeid(*this).name() << "class people is initialised\n";
}
~People(){
std::cout << typeid(*this).name() << "class people is destroyed\n";
}
private:
double worth;
};
int main(){
People Joe;
}
Responding to the comment:
People(std::string const& str)
: name(str)
{
std::cout << name << " class people is initialised\n";
}
////
int main(){
Person Joe("Joe");
}
Note this important difference:
People(std::string str) will create a copy of the string (which is usually expensive).
People(std::string const& str) will create a constant reference. Constant means it can not be changed and since it is a reference, it will not be copied here (it will be copied into the class member though).
You can use the preprocessor to get the name like this: typeid(*this).name().
P.S. Don't use using namespace std. It can make your code unclear.

Struggling with C++ "was not declared in this scope"

Can anyone tell me why i get the error "name was not declared in the scope when running this?
Thanks.
class lrn11_class{
public:
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string lrn11_name;
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
return 0;
}
This should work - see comments (BTW use std:: - Why is "using namespace std" considered bad practice?)
#include <iostream>
#include <string>
class lrn11_class{
public:
void setName(const std::string& x){ // Potentially saves copying overhead
name = x;
}
std::string getName() const { // Look up const and its uses
return name;
}
private:
std::string name; // - Used: string lrn11_name; but functions use name!
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setName("Zee"); // Fixed typo
std::cout << lrn11_nameobject.getName() << std::endl; // Ditto
return 0;
}
You have declare lrn11_name as a member varible for this class. But in set and get functions you are using name.
Other than than you need to call functions as you have defined.
so instead of :-
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
You have to use following code :-
lrn11_nameobject.setName("Zee");
cout << lrn11_nameobject.getName() << endl;
Make sure that
#include <iostream>
using namespace std;
should be included.

destructor ignore string assignment

I have created a program in C++ for a class, and one of the requirements is to output a string when certain parts of the program have been called. For most of these I have simply assigned a string to a member variable and then outputted that variable. I wanted to know is it possible for me to assign the string in a destructor and then output that string? When I try it, it outputs nothing.
ie:
Class
private:
string output;
~Class {
output = "destructor has fired!";
}
int main(){
cout << class.message;
}
This is pseudocode so please ignore syntax mistakes/missing pieces.
It certainly is possible to output a message in the destructor, to know that it has fired, and one way to do it is this...
#include <iostream>
#include <string>
using namespace std;
class C{
string output; // by default private
public:
C(){}
~C() { cout << output << endl; }
void setString(const string& s) {
output = s;
}
};
int main()
{
{
C s;
s.setString("Destructor has fired");
}
return 0;
}
If I understand your question right, this is what you are expected to do. Note: no member variable, direct calls to std::cout.
#include <iostream>
#include <string>
using namespace std;
class C{
public:
C() {
cout << "C ctor" << endl;
}
~C() {
cout << "C dtor" << endl;
}
};
int main()
{
{
C s;
}
return 0;
}

C++ header issue involving functions and scope

My problem is in the following C++ code. On the line with the 'cout' I get the error:
"'number' was not declared in this scope".
.h
using namespace std;
class a{
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
int main(){
cout << "Your number is: " << number() << endl;
return 0;
}
number(){
int x = 1;
return x;
}
Note: I'm aware this isn't the cleanest code. I just wanted to get the function working and refresh my memory on how to use headers.
For minimal fix, three basic changes are necessary.
Proper implementation of the number() method
int a::number() {
int x = 1;
return x;
}
Proper invocation of the number() method
a aObject;
cout << "Your number is: " << aObject.number() << endl;
There are many other enhancements possible though.
Addition, as pointed out by #CPlusPlus, usable scope of number() method, for example declaring it public
class a{
public:
int number();
};
Try this in your cpp file
using namespace std;
#include <iostream>
#include "header.h"
void a::number()
{
int x = 1;
return x;
}
int main()
{
cout << "Your number is: " << a().number() << endl;
return 0;
}
As for your header file replace class with a struct. The reason you are getting this error is because the compiler cant find the variable number. It is actually a method of a class.The reason you are replacing the class with a struct is because by default everything in a struct is public. So your header file called header.h should look like this
using namespace std;
struct a
{
int number();
};
There are three issues with your code.
The definition of the function number().
As you declared, it is a member function of the class "a". In your .cpp, the class name should be used as a prefix to the function. I mean,
a::number(){
int x = 1;
return x;
}
As the function is a member of the class "a", there are only two ways of accessing it,
If the function is a static function in the class, you can access it with :: operator. Like a::number().
If the function is not a static function, that is true in your case, you should instantiate the object out of the class "a" and they use "." operator with the reference. I mean,
a obj;
obj.number().
Your function number() is declared in private scope. You may recall that by default the scope is a class is private unless you specify public or protected. So the private function number() cannot be used outside the declared class unless there is a friend to it.
Below the code that I fixed,
.h
using namespace std;
class a{
public:
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
a::number(){
int x = 1;
return x;
}
int main(){
a obj;
cout << "Your number is: " << obj.number() << endl;
return 0;
}

c++ getter not returning changed value outside class

I have 1 main class
class Vehicle{
private:
int fuel;
public:
int get_fuel(){ return this->fuel; }
void set_fuel(int fuel){ this->fuel = fuel; }
};
also 1 subclass of Vehicle
class Car : public Vehicle{
public:
Car();
};
Car::Car(){
set_fuel(500);
}
also my main.cpp file
#include <cstdlib>
#include <iostream>
#include "Vehicle.h"
#include "Car.h"
using namespace std;
int main(int argc, char *argcv[]){
Car c;
cout << c.get_fuel() << endl; //500
//set fuel to 200
c.set_fuel(200);
//print fuel again
cout << c.get_fuel() << endl;//still 500
}
why after using the setter the value still remains the same after i use the getter?
On VC++ 2012 your exact code works as expected. Output is 500 and 200.
class Vehicle {
private:
int _fuel;
public:
Vehicle(){
_fuel = 0;
}
int get_fuel(){
return _fuel;
}
// I like chainable setters, unless they need to signal errors :)
Vehicle& set_fuel(int fuel){
_fuel = fuel;
return *this;
}
};
class Car : public Vehicle {
public:
Car():Vehicle(){
set_fuel(500);
}
};
// using the code, in your main()
Car car;
std::cout << car.get_fuel() << std::endl; // 500
car.set_fuel(200);
std::cout << car.get_fuel() << std::endl; // actually 200
This is a slightly modified version. Place it in your .CPP file and try it. It can't not work!
PS: Stop using properties that have the same name as arguments. Always having to use this-> is very not cool! When you'll forget to use the this->, you'll see the bug of the century when you'll assign the value to itself and can't figure out what goes wrong.