A6SE
A6SE

Reputation: 270

Four same ways of writing a method/function in C++?

Today at school we learned the four ways of writing the method/function in C++, but I'm not sure I understand the concept of each and how they differ. Do they all do the same thing?. The first code is the class declaration, and the second code is implementation outside of the class:

a)

1) Vector Addition(Vector a);

2) Vector Vector::Addition(Vector a)
{
    Vector temp = *this;
    temp.x+=a.x;
    temp.y+=a.y;
    return temp;
}

b)

1)Vector ConcreteInstanceAddition(Vector a, Vector b);

2) Vector Vector::ConcreteInstanceAddition(Vector a, Vector b)
{
    Vector temp=*this;
    temp.x=a.x+b.x;
    temp.y=a.y+b.y;
    return temp;
}

c)

1) friend Vector NonConcreteInstanceAddition(Vector a, Vector b);

2) Vector NonConcreteInstanceAddition(Vector a, Vector b)
{
    Vector temp(0,0);
    temp.x=a.x+b.x;
    temp.y=a.y+b.y;
    return temp;
}

d)

1) static Vector NonConcreteInstanceAdditionStatic(Vector a, Vector b);

2) Vector Vector::NonConcreteInstanceAdditionStatic(Vector a, Vector b)
{
    Vector temp(0,0);
    temp.x=a.x+b.x;
    temp.y=a.y+b.y;
    return temp;
}

And this is implementation in the main function:

Vector a(0,0),b(0,0),c(0,0);

c=a.Addition(b);
//or
c.ConcreteInstanceAddition(a,b);
//or
c=NonConcreteInstanceAddition(a,b);
//or
c=Vector::NonConcreteInstanceAdditionStatic(a,b);

Upvotes: 0

Views: 156

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57678

You forgot some more:
(Free standing, returns by parameter)

void Addition (const Vector& a, const Vector& b, Vector & result)
{
   result.x = a.x + b.x;
   result.y = a.y + b.y;
   return;
}

In the main function:

Addition(a, b, c);

There are also variations by using const and passing by reference.

Answers:
a) Member function; can use class variables without this->.
Modifies the "hosting" instance's member variables.

b) Member function; doesn't modify instance variables.

c) Free standing function with permission to access methods and variables in a class.

d) Static member function. Can be accessed without an object instance, but cannot access any class variables. (Class variables require an instance.)

Edit 1: You can also add in two more by implementing operator+=() and operator+().

Edit 2: Usage of static member function

c = Vector::NonConcreteInstanceAdditionStatic(a,b);

The Static Member Function is like using a free standing function, except it is inside of a class and must use the scope resolution operator, ::, to access.

Upvotes: 1

Related Questions