Fred Tingaud 22b4470f2a
Modify CFamily rules: CPP-4080 Refresh and standardize CppCoreGuidelines references (#3514)
Update all links to C++ Core Guidelines to `e49158a`.

Refresh done using the following script and some manual edits:
db76e34e74/personal/fred-tingaud/rspec/refresh-cppcoreguidelines.py

When re-using this script, be mindful that:
 - it does not cover `shared_content`
 - it does not properly escape inline code in links (e.g., "[=]" or "`mutex`es")
 - it does not change `C++` to `{cpp}` in link titles.

Co-authored-by: Marco Borgeaud <marco.borgeaud@sonarsource.com>
2023-12-20 10:08:18 +01:00

80 lines
2.1 KiB
Plaintext

== Why is this an issue?
When inheriting from a class, if you need to inherit its constructors without additional initialization you should prefer ``++using-declaration++`` to inherit all base class's constructors instead of writing them by hand.
``++using-declaration++`` for inheriting constructor is a {cpp}11 feature that makes all constructors of the base visible to the overload resolution when initializing the derived class.
If you need to change the accessibility of one of the inherited constructors, you can do it by keeping the ``++using-declaration++`` and declaring that constructor explicitly as private:
----
class Base {
public:
Base(int p) {}
Base(int p1, int p2) {}
};
class Derived : public Base {
using Base::Base;
Derived(int p1, int p2); // Changes constructor to private accessibility
};
int f(){
Derived b(1); // Base(int p) is visible when initializing the derived class
Derived b1(1,2); // Compilation error: Base(int p1, int p2) is not visible when initializing the derived class
}
----
This rule raises an issue when a constructor inherits the base class constructor without requiring any additional initialization.
=== Noncompliant code example
[source,cpp]
----
class Base {
public:
Base(int p) {}
};
class Derived : public Base {
public:
Derived(int p) : Base(p) {} // Noncompliant
};
----
=== Compliant solution
[source,cpp]
----
class Base {
public:
Base(int p) {}
};
class Derived : public Base {
using Base::Base;
};
----
== Resources
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#c52-use-inheriting-constructors-to-import-constructors-into-a-derived-class-that-does-not-need-further-explicit-initialization[C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace inherited constructors without additional initialization by a "using" declaration.
endif::env-github,rspecator-view[]