1
1
123qwe2015-10-25 21:16:22
Java
123qwe, 2015-10-25 21:16:22

What is the equivalent of Java interfaces in C++?

What's up, software.
In C++, when defining a class in a header file, we can declare an empty constructor.
At the same time, in the source file, we can define this constructor using the so-called "binary scope resolution operator ( :: )", which in turn reminds me of a Java interface.
Example:
person.h - file

class Person
{
public:
    Person();
}
_______________________________
Person.cpp - file
#include"Person.h"
Person::person(int i)
{
    int k = i;
}
_______________________________
AnotherPerson.cpp - file
#include"Person.h"

Person::Person(int n, int j)
{
    int a = n;
    int b = j;
}

In the file with the main method, I can create an instance of the Person class, and use different constructors, in this case there are 2 of them, i.e. it would look something like this:
#include "Person.h"

int main()
{
    Person one;
    Person two;

    one(1);
    two(2,3);

   std::cout << one << std::endl;
   std::cout << two << std::endl;
}

I immediately apologize for the mistakes in the code, but the main thing is that the meaning is clear, and most importantly, do I understand it correctly.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Armenian Radio, 2015-10-25
@gbg

Do not drag knowledge of java into C ++. Get yourself in trouble.
If you want to have constructors with different sets of parameters - declare them all in the header and give them bodies in cpp.

J
jcmvbkbc, 2015-10-25
@jcmvbkbc

What is the analog of Java interfaces in C++

Classes without data and only with pure virtual functions.
Some nonsense is written in the examples: you cannot define or call undeclared class methods, and you have not declared constructors with one and two parameters.

S
Stanislav Makarov, 2015-10-26
@Nipheris

recursi0n good night. Please read my answer to a similar question: ClassName::functionName or objectName.functionName? You will surely find something for yourself.

I
Ilya Popov, 2015-10-26
@encyclopedist

In C++, the notation
just means that B is inside A, where A is a namespace, class, or enum. B can be a function, a class, a static variable. (see cppreference ) This notation has no special meaning for constructors. It also has nothing to do with interfaces.
Interfaces in C++ are analogous to analogous to abstract classes :

class Interface {
public:
    virtual int method() = 0;
};

class Implementation: public Interface{
public:
    int method() override {
         // some code
    }
};

PS: as already mentioned, trying to transfer some habits from one language to another or find analogues for everything usually does not lead to anything good. Learn C++ as if from scratch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question