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;
}
Related
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.
I show you the code directly.
#include <iostream>
#include <stdio.h>
class A {
public:
A(const std::string& name){
std::string aname = "HAHA_" + name;
std::cout << aname << std::endl;
}
~A(){
std::cout << "Done." << std::endl;
}
};
int main() {
size_t len = 5;
char szTmp[30] ={0};
snprintf(szTmp,sizeof(szTmp),"Getlist_V2_%zd",len);
A a(std::string(szTmp));
return 0;
}
The expected results are as follows:
HAHA_Getlist_V2_5
Done.
But It outputs nothing at all. When I replace A a(std::string(szTmp)); with
A a(szTmp); ,erverything is ok. It confused me for a long time.
A a(std::string(szTmp));
This is a function declaration, believe it or not! So, no A is constructed.
Instead, write this:
A a{std::string(szTmp)};
Or, since an implicit conversion to std::string exists, either of the following will suffice:
A a{szTmp};
A a(szTmp);
I have searched but still didn't get easy and proper answer, Below is my code.
#include <iostream>
using namespace std;
class Parent
{
private:
int a;
public:
Parent():a(3) { cout << a; }
};
int main()
{
Parent obj;
return 0;
}
Can you add additional lines of code that can prove or show me that initializer list call before constructor?
I would modify you code ever so slightly:
#include <iostream>
using namespace std;
class Parent
{
public:
int a;
public:
Parent():a(3){
a = 4;
}
};
int main()
{
Parent obj;
cout << obj.a;
return 0;
}
The output is 4, thus a was initialized with 3 and then assigned 4.
Simply add data member, which has constructor, which prints something. Example:
#include <iostream>
using namespace std;
struct Data {
Data(int a) {
cout << "Data constructor with a=" << a << endl;
}
};
class Parent
{
private:
Data a;
public:
Parent():a(3){
cout << "Parent constructor" << endl;
}
};
int main()
{
Parent obj;
return 0;
}
Output:
Data constructor with a=3
Parent constructor
Conclusion: Data constructor was called before constructor body of Parent.
You don't get variable "a" value 10 in this program , a assigned before constructor method called .
#include<iostream>
using namespace std;
class Test
{
public:
int a,b;
public:
Test():a(b){
b=10;
}
};
int main()
{
Test obj;
cout<<"a :"<<obj.a<<" b:"<<obj.b;
return 0;
}
This is best shown with multiple classes:
#include <iostream>
class A
{
public:
A()
{
std::cout << "Hello World!" << std::endl;
}
};
class B
{
private:
A* a;
public:
// Call a's constructor
B():a(new A)
{
// Some code
}
~B()
{
delete a;
}
};
int main()
{
B obj;
return 0;
}
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;
}
I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.