create an instance of a class c++ code example
Example 1: declaring instance of class c++
#include <iostream>
using namespace std;
class Foo
{
public:
Foo ( )
{
cout << "constructor Foo\n";
}
};
class Bar
{
public:
Bar ( Foo )
{
cout << "constructor Bar\n";
}
};
int main()
{
Foo* foo1 = new Foo ();
Foo* foo2 = new Foo;
Foo foo3;
Foo foo4 = Foo::Foo();
Bar* bar1 = new Bar ( *new Foo() );
Bar* bar2 = new Bar ( *new Foo );
Bar* bar3 = new Bar ( Foo foo5 );
Bar* bar3 = new Bar ( Foo::Foo() );
return 1;
}
Example 2: how to write a class in c++
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y)
{
width = x;
height = y;
}