How to preprocess more in C/C++ [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I was wondering, and some people with a lot more knowledge than me will probably know the answer :
Why isn't the C (in my case its for C++) preprocessor more complete ?
What I mean is why couldn't we use for example C++ as the preprocessor language ? It would allow us to do so much more about classes, generate dynamic code etc...
Ideally I would want to call a C++ function just like a preprocessor macro, with a concrete example, I would like to do things like:
#void generateVariable(std::string type, std::string name) {
# if (name[0] == 'p')
# cout << "protected:" << endl << type << " " << name << ";" << endl;
# if (name[0] == 'm')
# cout << "public:" << endl << type << " " << name << ";" << endl;
# std::string prefix = name;
# prefix.erase(2, npos);
# name.erase(0,2);
# name[0] = toupper(name[0]);
# cout << "public:" << endl << type << "get" << name << "() const { return " << prefix+name << "; }" << endl;
#}
So that I could call
class A {
generateVariable(static const int, p_age)
}
And it would generate
class A {
protected:
static const int p_age;
public:
static const int getAge() const { return p_age; }
}
Are there actually ways to do this kind of thing, whithout parsing the whole file with a scripting language and rewriting it ?

The preprocessor actually can do this (though I wouldn't recommend to do so):
#define generateVariable(__type__, __name__) \
protected: __type__ __name__; \
public: __type__ get##__name__() { return __name__; }
class A {
generateVariable(static const int, p_age);
}
get##__name__() will expand to getp_age() though ...

Related

Why in pass by value there are multiple constructors(is it because of copy constructor)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
Consider this code:
class cl{
int id;
public:
int i;
cl(int i);
~cl();
void neg(cl o){
o.i=-o.i;
}
};
cl::cl(int num){
cout << "Constructing: " << num << endl;
id = num;
}
cl::~cl(){
cout << "Destructing: " << id << endl;
}
int main() {
cl o1(1);
o1.i = 10;
o1.neg(o1);
cout << o1.i << endl;
return 0;
}
Can anyone explain it? While passing by address, it creates a single constructor and destructor.
I need some explanation of the code working.

How can you print integers from a class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
This seems like a simple thing to me, but I have an entity class:
class Entity
{
private:
std::string m_Name;
public:
int x = 0, y = 0;
Entity() : m_Name("Undefined Entity") {
std::cout << m_Name << " Created!\n";
}
Entity(const std::string& name) : m_Name(name) {
std::cout << m_Name << " Created!\n";
}
~Entity() {
std::cout << m_Name << " Destroid\n";
}
const std::string GetName() { return m_Name; }
void PrintCords() { std::cout << x << ' , ' << y << '\n'; }
};
and in my main function I run the PrintCords function:
int main(void)
{
std::unique_ptr<Entity> j = std::make_unique<Entity>("Jeff");
std::cout << j->GetName() << '\n';
j->PrintCords();
}
Yet, when I run the program, I get seemingly random numbers:
021084480
You should compile with -Werror. This turns your warnings into errors. When you do this, you will see the following error:
prog.cpp:25:43: warning: multi-character character constant [-Wmultichar]
void PrintCords() { std::cout << x << ' , ' << y << '\n'; }
^~~~~
Which should indicate to you that something is wrong. If you change this to a string literal:
void PrintCords() { std::cout << x << " , " << y << '\n'; }
---> ^ ^
Then everything will be ok.

std::ofstream won't write to file (sometimes) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've gone over many questions with the same or similar titles, I have changed the code in so many ways I can't even count.... I have an interesting problem.
I have a class for logging that is extremely simple and just writes stuff into a file. The exact same code works in the constructor, but will not work in the member function. I'm stripping out some irrelevant code, the rest is:
private:
std::string logfile_path_;
std::string program_name_;
std::string GetTimestamp() {
timeval tv;
gettimeofday(&tv, NULL);
char cTimestamp[24];
strftime(cTimestamp, sizeof(cTimestamp), "%F %T", std::localtime(&tv.tv_sec));
sprintf(&cTimestamp[19], ".%03d", (tv.tv_usec / 1000)); // write the miliseconds (microseconds/1000) into cTimestamp starting at the 20th character. %03d == pad with 0, for a minimum length of 3, an integer.
return cTimestamp; // function returns std::string so this will be implicitly cast into a string and returned.
}
public:
int log_level_;
SrxDsLog(std::string Logfile_path, std::string program_name, int log_level) {
log_level_ = log_level;
program_name_ = program_name;
logfile_path_ = Logfile_path;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
std::cout << "Logger started, Log file: " << logfile_path_ << std::endl;
logfile << "Logger started, Log file: " << logfile_path_ << std::endl;
return;
}
void WriteLog(std::string Log_message, int Severity = LOG_CRITICAL, std::string Function_name = "") {
if (Severity >= log_level_) {
std::cout << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
logfile << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
}
}
The question is why is it working in the constructor, but the exact same code is not working in the member function. The std::cout is writing the exact same log message I want, but it's not appearing in the file. The file contains a single line every time the program is run.
In an amazingly unsatisfying turn of events I voted to close my question.
The problem was apparently caused by undefined behavior in unrelated code. And that because I did something that's defined in C++11 but is not in C++03. Apparently you can't call constructors from constructors in C++03....
Because of that, and because the question didn't include the code that was actually at fault, the question seems incredibly bad.
Please close.
int log_level_;
The constructor fails to initialize this class member.
Subsequently, the comparison with this class member results in undefined behavior.

How to call an object of class in global function in c++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a global function void start_menu() which I'm using as an interface.
void start_menu()
{
int x;
cout << " ------------------------------------" << endl;
cout << " WELCOME TO LIBRARY MANAGEMENT SYSTEM" << endl;
cout << "------------------------------------" << endl;
cout << " 1. ABOUT Books " << endl;
cout << " 2. ABOUT Members " << endl;
cout << " CHOOSE:";
cin >> x;
Books MyBooks; //object of books class
do
{
if (x==1)
{
system("cls");
MyBooks.INTR_Books(); //calling function of Books Class
}
};
}
Then, I have class Books{} which I want to be called in global function void start_menu() but when I make an object of Books class, which is defined as Books MyBooks;, the above code gave me this error:
error: 'Books' was not declared in this scope.
This is Books class after the global function void start_menu():
class Books
{
public:
string BookName; //name of the Book
string Auth; //Author of the book
string Trans; // translator of the book
string myArray[20];
int BookCode; // code of the book
int BookNum; // number of copies exist
void INTR_Books(); //show interface related to books
void ADD_BOOK();
void DELETE_BOOK();
void SEARCH();
void SHOW_ALL();
void BR_BOOK();
};
based on comments ,i had undrestood which Booksclass should be called after void start_menu() global function.

Facing error in c++ code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am writing code of ACM problem in which we have to check possibilities of different items. It's some minor error in the code.
#include<iostream>
using namespace std;
void CheckPossibilities( int numItems, int maxWeights )
{
if( numItems <= 0 )
{
cout << "Invalid Items";
}
if ( maxWeights <= 0 )
{
cout << "Impossible";
}
while( maxWeights > 0 )
{
if(numItems%2==0) //for even
{
numItems = numItems / 2;
maxWeights--;
}
else
{
numItems = (numItems -1)/ 2; //for odd
maxWeights--;
}
}
if( numItems <= 1 )
{
cout << "Possible";
}
else
{
cout << "Impossible";
}
}
void main()
{
int numItems1,maxWeights1;
cout<<"enter numItems"<<endl;
cin>>numItems1;
cout<<"maxWeights"<<endl;
cin>>maxWeights1;
cout<<numItems1 "AND" maxWeights1<<endl;
cout<<CheckPossibilities(numItems1, maxWeights1);
}
Your mistakes were trying to cout multiple strings in one line without concatting them in some way, either seperate with a << or a +. You also cant cout a void function because it tries to output void, you just need to call it and let the function do the outputting. With errors fixed the main should be
int main()
{
int numItems1,maxWeights1;
cout<<"enter numItems"<<endl;
cin>>numItems1;
cout<<"maxWeights"<<endl;
cin>>maxWeights1;
cout<<numItems1+"AND"+maxWeights1<<endl;
CheckPossibilities(numItems1, maxWeights1);
return 0;
}
Next time look at what line the error is thrown on when compiling and search those specific error because these were really simple and specific syntax errors that could be found by a google search easily.
void main()
{
int numItems1, maxWeights1;
cout << "enter numItems" << endl;
cin >> numItems1;
cout << "maxWeights" << endl;
cin >> maxWeights1;
cout << numItems1 << "AND" << maxWeights1 << endl;
CheckPossibilities(numItems1, maxWeights1);
}
you can never do this: cout<<CheckPossibilities(numItems1, maxWeights1); cout take standard output stream, not functions. And also you forgot to put << in cout << numItems1 << "AND" << maxWeights1 << endl; in this form, your code build succesful.