Constructor called outside of main - c++

I saw this question about constructors and I don't understand why the variable a is calling the constructor.
I thought it wass an error because the variable declaration is out of main without stating global before the name of it and they only wrote a; without the class name before it. How does the compiler know that the variable is of type Test?
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout << "Hello from Test() "; }
} a;
int main()
{
cout << "Main Started ";
return 0;
}
The answer for the output was - "Hello from Test() Main Started".

As you might know, we have two ways to create an object from the Test class:
first, in the main:
class Test
{
public:
Test() { cout << "Hello from Test() "; }
};
int main()
{
Test a;
cout << "Main Started ";
return 0;
}
Or before starting main in the definition of your class (like your code):
class Test
{
public:
Test() { cout << "Hello from Test() "; }
} a;
int main()
{
cout << "Main Started ";
return 0;
}
In both cases, you are calling the constructor of the Test class once you make an object from it. In the main or before it.

Related

Global Array in C++

Can anybody tell me what is wrong in the following code when I initialize a global array and want to print its value outside main() function
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
cout << global_array[2];
int main()
{
cout << "Hello World!" ;
}
The error keep popping is
error: 'cout' does not name a type|
The statement cout << global_array[2]; is not a declaration (it is an expression). Only declarations are allowed outside of functions.
So, if you want to print anything outside of main function, you can only do so by having the expression within another function.
I think the problem is that the code you have that does the printing is outside of any function. Statements in C++ need to be inside a function. For example:
#include <iostream>
using namespace std;
void hello();
int global_array[5] = {10,20,30,40,50};
void hello()
{
cout << global_array[2];
}
int main()
{
hello();
cout << "Hello World!" ;
}
Before asking a question, you can search: ‘cout’ does not name a type
Thanks you.
if you want to call it from outside the main it should be in a function something like this
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
int pre()
{
cout << global_array[2];
return 0;
}
int x = pre();
int main()
{
cout<<"Hello World";
return 0;
}
as i mentioned it on comment it can be done via c++ classes.
#include <iostream>
int global_array[5] = { 10,20,30,40,50 };
struct foo
{
foo()
{
std::cout << global_array[2] << std::endl;
}
};
foo f;
int main()
{
}

Propose to the user to rewrite functions with lambda

I'm doing tests to understand lambdas. I am trying to offer to the users the ability to rewrite a function directly in the main function. Let me explain:
#include <iostream>
using namespace std;
class A {
public:
virtual bool execute() {};
};
class B : public A {
public:
bool execute() { cout << "Execute in B" << endl; }
};
int main() {
B newB;
newB.execute();
newB.execute() { cout << "Execute in New B" << endl; } ;
newB.execute();
return 0;
}
This source code doesn't work because it's illegal to rewrite a function like that. What would be for you, the best way to rewrite a function like that in C ++ 14? With lambda? Without lambda?
I want do like in Javascript, overloading a function like that: newB.somefunction = function(...) { ... };. I want the function to be written in source code by a user of my Library. In a way a callback function.
my question is the following: How to write a callback function or Lambda expressions to rewrite a method outside a class/object?
Solution proposed by Exagon with variable :
#include <iostream>
#include <functional>
class B {
public:
int global=0;
std::function<void()> execute{
[](){
std::cout << "Hello World" << std::endl;
}
};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.execute = [newB](){std::cout << newB.global << " = FOOBAR\n";};
newB.execute();
return 0;
}
You can do this using std::function from the functional header.
Then make a std::function member and create a setter for this member.
the execute member function need to call this std::function member.
you can pass a lambda into the setter method.
here is my approach:
#include <iostream>
#include <functional>
class B {
public:
void execute() {_f();}
void setFunction(std::function<void()> f){ _f = f;}
private:
std::function<void()> _f{[](){std::cout << "Hello World" << std::endl;}};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.setFunction([](){std::cout << "FOOBAR\n";});
newB.execute();
return 0;
}
the output is:
Hello World
Hello World
FOOBAR
Since you are after something "JavaScript-like" you could do it like this:
#include <iostream>
#include <functional>
class B {
public:
std::function<void()> execute{
[](){
std::cout << "Hello World" << std::endl;
}
};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.execute = [](){std::cout << "FOOBAR\n";};
newB.execute();
return 0;
}
Which has the same output.
here is a live demo

How to invoke a C++ function after main() finishes

I am developing a C++ tool that should run transparent to main program. That is: if user simply links the tool to his program the tool will be activated. For that I need to invoke two functions, function a(), before main() gets control and function b() after main() finishes.
I can easily do the first by declaring a global variable in my program and have it initialize by return code of a(). i.e
int v = a() ;
but I cannot find a way to call b() after main() finishes?
Does any one can think of a way to do this?
The tool runs on windows, but I'd rather not use any OS specific calls.
Thank you, George
Use RAII, with a and b called in constructor/destructor.
class MyObj {
MyObj()
{
a();
};
~MyObj()
{
b();
};
};
Then just have an instance of MyObj outside the scope of main()
MyObj obj;
main()
{
...
}
Some things to note.
This is bog-standard C++ and will work on any platform
You can use this without changing ANY existing source code, simply by having your instance of MyObj in a separate compilation unit.
While it will run before and after main(), any other objects constructed outside main will also run at this time. And you have little control of the order
of your object's construction/destruction, among those others.
SOLUTION IN C:
have a look at atexit:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void bye(void)
{
printf("That was all, folks\n");
}
int main(void)
{
long a;
int i;
a = sysconf(_SC_ATEXIT_MAX);
printf("ATEXIT_MAX = %ld\n", a);
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
http://linux.die.net/man/3/atexit
this still implies however that you have access to your main and you can add the atexit call. If you have no access to the main and you cannot add this function call I do not think there is any option.
EDIT:
SOLUTION IN C++:
as sudgested there is a c++ equivalent from std. I simply paste in here an example which i copied from the link available just below the code:
#include <iostream>
#include <cstdlib>
void atexit_handler_1()
{
std::cout << "at exit #1\n";
}
void atexit_handler_2()
{
std::cout << "at exit #2\n";
}
int main()
{
const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);
if ((result_1 != 0) or (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
std::cout << "returning from main\n";
return EXIT_SUCCESS;
}
http://en.cppreference.com/w/cpp/utility/program/atexit
Isn't any global variable constructed before main and destructed afterward? I made a test struct whose constructor is called before main and the destructor afterward.
#include <iostream>
struct Test
{
Test() { std::cout << "Before main..." << std::endl; }
~Test() { std::cout << "After main..." << std::endl; }
};
Test test;
int main()
{
std::cout << "Returning now..." << std::endl;
return 0;
}
If you're happy to stick with a single compiler and non-standard C/C++, then GCC's __attribute__((constructor)) and __attribute__((destructor)) might be of use:
#include <stdio.h>
void __attribute__((constructor)) ctor()
{
printf("Before main()\n");
}
void __attribute__((destructor)) dtor()
{
printf("After main()\n");
}
int main()
{
printf("main()\n");
return 0;
}
Result:
Before main()
main()
After main()
Alternatively to the destructor, you can use atexit() in a similar manner - in C++, you do not need to have access to main() to register atexit there. You can do that as well it in your a() - for example:
void b(void) {
std::cout << "Exiting.\n";
}
int a(void) {
std::cout << "Starting.\n";
atexit(b);
return 0;
}
// global in your module
int i = a();
That being said, I'd also prefer the global C++ class object, which will call the b() stuff in its destructor.

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;
}

Any Example that Prove Initializer List Call before Constructor C++

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;
}