16.4 — Association – Learn C++ (2023)

In the previous two lessons, we’ve looked at two types of object composition, composition and aggregation. Object composition is used to model relationships where a complex object is built from one or more simpler objects (parts).

In this lesson, we’ll take a look at a weaker type of relationship between two otherwise unrelated objects, called an association. Unlike object composition relationships, in an association, there is no implied whole/part relationship.

Association

To qualify as an association, an object and another object must have the following relationship:

  • The associated object (member) is otherwise unrelated to the object (class)
  • The associated object (member) can belong to more than one object (class) at a time
  • The associated object (member) does not have its existence managed by the object (class)
  • The associated object (member) may or may not know about the existence of the object (class)

Unlike a composition or aggregation, where the part is a part of the whole object, in an association, the associated object is otherwise unrelated to the object. Just like an aggregation, the associated object can belong to multiple objects simultaneously, and isn’t managed by those objects. However, unlike an aggregation, where the relationship is always unidirectional, in an association, the relationship may be unidirectional or bidirectional (where the two objects are aware of each other).

(Video) C++ Tutorial | Learn C++ programming | Full C++ Programming Course

The relationship between doctors and patients is a great example of an association. The doctor clearly has a relationship with his patients, but conceptually it’s not a part/whole (object composition) relationship. A doctor can see many patients in a day, and a patient can see many doctors (perhaps they want a second opinion, or they are visiting different types of doctors). Neither of the object’s lifespans are tied to the other.

We can say that association models as “uses-a” relationship. The doctor “uses” the patient (to earn income). The patient uses the doctor (for whatever health purposes they need).

Implementing associations

Because associations are a broad type of relationship, they can be implemented in many different ways. However, most often, associations are implemented using pointers, where the object points at the associated object.

In this example, we’ll implement a bi-directional Doctor/Patient relationship, since it makes sense for the Doctors to know who their Patients are, and vice-versa.

(Video) C++ Tutorial for Beginners | Learn C++ Programming Language | Introduction to C++ | Edureka

#include <functional> // reference_wrapper#include <iostream>#include <string>#include <vector>// Since Doctor and Patient have a circular dependency, we're going to forward declare Patientclass Patient;class Doctor{private:std::string m_name{};std::vector<std::reference_wrapper<const Patient>> m_patient{};public:Doctor(const std::string& name) :m_name{ name }{}void addPatient(Patient& patient);// We'll implement this function below Patient since we need Patient to be defined at that pointfriend std::ostream& operator<<(std::ostream& out, const Doctor& doctor);const std::string& getName() const { return m_name; }};class Patient{private:std::string m_name{};std::vector<std::reference_wrapper<const Doctor>> m_doctor{}; // so that we can use it here// We're going to make addDoctor private because we don't want the public to use it.// They should use Doctor::addPatient() instead, which is publicly exposedvoid addDoctor(const Doctor& doctor){m_doctor.push_back(doctor);}public:Patient(const std::string& name): m_name{ name }{}// We'll implement this function below to parallel operator<<(std::ostream&, const Doctor&)friend std::ostream& operator<<(std::ostream& out, const Patient& patient);const std::string& getName() const { return m_name; }// We'll friend Doctor::addPatient() so it can access the private function Patient::addDoctor()friend void Doctor::addPatient(Patient& patient);};void Doctor::addPatient(Patient& patient){// Our doctor will add this patientm_patient.push_back(patient);// and the patient will also add this doctorpatient.addDoctor(*this);}std::ostream& operator<<(std::ostream& out, const Doctor& doctor){if (doctor.m_patient.empty()){out << doctor.m_name << " has no patients right now";return out;}out << doctor.m_name << " is seeing patients: ";for (const auto& patient : doctor.m_patient)out << patient.get().getName() << ' ';return out;}std::ostream& operator<<(std::ostream& out, const Patient& patient){if (patient.m_doctor.empty()){out << patient.getName() << " has no doctors right now";return out;}out << patient.m_name << " is seeing doctors: ";for (const auto& doctor : patient.m_doctor)out << doctor.get().getName() << ' ';return out;}int main(){// Create a Patient outside the scope of the DoctorPatient dave{ "Dave" };Patient frank{ "Frank" };Patient betsy{ "Betsy" };Doctor james{ "James" };Doctor scott{ "Scott" };james.addPatient(dave);scott.addPatient(dave);scott.addPatient(betsy);std::cout << james << '\n';std::cout << scott << '\n';std::cout << dave << '\n';std::cout << frank << '\n';std::cout << betsy << '\n';return 0;}

This prints:

James is seeing patients: DaveScott is seeing patients: Dave BetsyDave is seeing doctors: James ScottFrank has no doctors right nowBetsy is seeing doctors: Scott

In general, you should avoid bidirectional associations if a unidirectional one will do, as they add complexity and tend to be harder to write without making errors.

Reflexive association

Sometimes objects may have a relationship with other objects of the same type. This is called a reflexive association. A good example of a reflexive association is the relationship between a university course and its prerequisites (which are also university courses).

Consider the simplified case where a Course can only have one prerequisite. We can do something like this:

(Video) The Design of C++ , lecture by Bjarne Stroustrup

#include <string>class Course{private: std::string m_name; const Course* m_prerequisite;public: Course(const std::string& name, const Course* prerequisite = nullptr): m_name{ name }, m_prerequisite{ prerequisite } { }};

This can lead to a chain of associations (a course has a prerequisite, which has a prerequisite, etc…)

Associations can be indirect

In all of the previous cases, we’ve used either pointers or references to directly link objects together. However, in an association, this is not strictly required. Any kind of data that allows you to link two objects together suffices. In the following example, we show how a Driver class can have a unidirectional association with a Car without actually including a Car pointer or reference member:

#include <iostream>#include <string>class Car{private:std::string m_name;int m_id;public:Car(const std::string& name, int id): m_name{ name }, m_id{ id }{}const std::string& getName() const { return m_name; }int getId() const { return m_id; }};// Our CarLot is essentially just a static array of Cars and a lookup function to retrieve them.// Because it's static, we don't need to allocate an object of type CarLot to use itclass CarLot{private:static Car s_carLot[4];public:CarLot() = delete; // Ensure we don't try to create a CarLotstatic Car* getCar(int id){for (int count{ 0 }; count < 4; ++count){if (s_carLot[count].getId() == id){return &(s_carLot[count]);}}return nullptr;}};Car CarLot::s_carLot[4]{ { "Prius", 4 }, { "Corolla", 17 }, { "Accord", 84 }, { "Matrix", 62 } };class Driver{private:std::string m_name;int m_carId; // we're associated with the Car by ID rather than pointerpublic:Driver(const std::string& name, int carId): m_name{ name }, m_carId{ carId }{}const std::string& getName() const { return m_name; }int getCarId() const { return m_carId; }};int main(){Driver d{ "Franz", 17 }; // Franz is driving the car with ID 17Car* car{ CarLot::getCar(d.getCarId()) }; // Get that car from the car lotif (car)std::cout << d.getName() << " is driving a " << car->getName() << '\n';elsestd::cout << d.getName() << " couldn't find his car\n";return 0;}

In the above example, we have a CarLot holding our cars. The Driver, who needs a car, doesn’t have a pointer to his Car -- instead, he has the ID of the car, which we can use to get the Car from the CarLot when we need it.

In this particular example, doing things this way is kind of silly, since getting the Car out of the CarLot requires an inefficient lookup (a pointer connecting the two is much faster). However, there are advantages to referencing things by a unique ID instead of a pointer. For example, you can reference things that are not currently in memory (maybe they’re in a file, or in a database, and can be loaded on demand). Also, pointers can take 4 or 8 bytes -- if space is at a premium and the number of unique objects is fairly low, referencing them by an 8-bit or 16-bit integer can save lots of memory.

(Video) Bjarne Stroustrup: C++ | Lex Fridman Podcast #48

Composition vs aggregation vs association summary

Here’s a summary table to help you remember the difference between composition, aggregation, and association:

PropertyCompositionAggregationAssociation
Relationship typeWhole/partWhole/partOtherwise unrelated
Members can belong to multiple classesNoYesYes
Members’ existence managed by classYesNoNo
DirectionalityUnidirectionalUnidirectionalUnidirectional or bidirectional
Relationship verbPart-ofHas-aUses-a
Next lesson16.5DependenciesBack to table of contentsPrevious lesson16.3Aggregation
(Video) Pointers in C / C++ [Full Course]

FAQs

How much time should I spend learning C++? ›

You can expect to master the syntax of C++ in about two to three months if you devote about 10 hours every week to learning C++. However, to become highly proficient at programming in C++, expect to spend at least one year studying full-time.

What is association in C++ with example? ›

An association supports data sharing between classes or, in the case of a self-association, between objects of the same class. For example, a Customer class has a single association (1) to an Account class, indicating that each Account instance is owned by one Customer instance.

What is association with example? ›

An example of an association

An example of a relationship is a one-to-many association between departments and employees. They might have a relationship where the Dept entity object has a Deptno attribute that is related to the Deptno attribute of the Emp entity object (Dept. Deptno = Emp.

Is C++ enough to get a job? ›

Job opportunities: C++ is a very popular coding language, and millions of programmers use it in companies all over the world. This means that there are often many work opportunities for skilled C++ programmers.

Is C++ very difficult to learn? ›

C++ is hard to learn because of its multi-paradigm nature and more advanced syntax. While it's known to be especially difficult for beginners to learn, it's also difficult for programmers with no experience with low-level languages.

What are the 3 types of association define each? ›

The three types of associations include: chance, causal, and non-causal. A chance association refers to an association that is random and fake, such as an associating an increase in the consumption of soda with an increase in the rate of crime in a nation.

Why do we use association? ›

Associations Provide Opportunities to Meet and Engage with Peers and Colleagues. To me, this is the most important benefit associations can provide. Associations are made up of people who share similar challenges and opportunities.

What is association in coding? ›

Association in object oriented programming

An association is a “using” relationship between two or more objects in which the objects have their own lifetime and there is no owner.

What's the hardest coding language? ›

Haskell. The language is named after a mathematician and is usually described to be one of the hardest programming languages to learn. It is a completely functional language built on lambda calculus.

Can I learn C++ in a month? ›

It takes around 1 to 3 months to learn the basics and syntax of C++ programming. Gaining mastery in the C++ programming language can take around 2 years.

Is C++ easy than Python? ›

C++ is a bit complex when it comes to the simplicity of language, and it has more syntax rules as well as program conventions. Python is a friendly language. It has a simple and easy-to-learn syntax. Moreover, its features are easy to use, which allows you to write short and readable code.

How do you use association? ›

Example Sentences

an association of local business leaders They denied having any association with terrorists. They have a long association with the school and have donated millions of dollars to it.

How does association work? ›

Associations exist to establish strength and unity in working toward a common goal. They are nonprofit organizations formed to promote the economic, scientific or social well being of their members. Different types of associations cater to diverse industries professions and causes.

What are the four different types of association? ›

These four types of associations-performance, sociable, symbolic (or ideological), and productive-are quite distinct species of social organization, and each represents a distinct form of social integration.

Is C++ high paying? ›

8 - C/C++ C/C++ holds a solid top 8 spot with an average salary of ~$109K per year. Its usage in the industry is widely extended, C++ can be found on video games, servers, databases, space probes and many others.

How much does a C++ programmer make a year? ›

How much does a C++ Programmer make in the United States? The average C++ Programmer salary in the United States is $78,054 as of December 27, 2022, but the salary range typically falls between $70,077 and $82,457.

What is the salary of a C++ developer? ›

How much does a Developer C/C++ make? The national average salary for a Developer C/C++ is ₹7,00,000 in India.

Is C++ or Python harder? ›

Is C++ Harder Than Python? Yes, C++ is harder to learn and work with than Python . The biggest difference is that C++ has a more complex syntax to work with and involves more memory management than Python, which is both simple to learn and use. Python is considered a better beginner programming language.

Is C++ or Java harder? ›

Most experts will tell you that Java is easier to learn. It's a newer language than C++ and isn't as complex in its principles or execution. However, there's more to consider than a language's learning curve. Selecting a programming language comes down to what you want to do with it.

Is studying C++ worth it? ›

It is a versatile language, so it remains in high demand amongst professionals, such as software developers, game developers, C++ analysts and backend developers, etc. As per the TIOBE index of 2022, C++ lies at 4th position in the world's most popular language.

What is association type? ›

An association type (also called an association) is the fundamental building block for describing relationships in the Entity Data Model (EDM). In a conceptual model, an association represents a relationship between two entity types (such as Customer and Order ).

What are the three laws of association? ›

David Hume proposed three different laws of association: resemblance, contiguity in time or place, and cause or effect (Hume, 1748/1952).

How does association help with learning? ›

Associative learning is a learning principle that states that ideas and experiences reinforce each other and can be mentally linked to one another. In a nutshell, it means our brains were not designed to recall information in isolation; instead, we group information together into one associative memory.

What is the power of association? ›

The Power of Associations documents the unique contributions of membership organizations to America's economy and civic life. Their economic benefits include more than 1.3 million jobs; a total payroll of nearly $51 billion; and tangible contributions to national, state, and local economies.

What is association rule learning used for? ›

Association rule learning is a rule-based machine learning method for discovering interesting relations between variables in large databases. It is intended to identify strong rules discovered in databases using some measures of interestingness.

What is association class example? ›

An association class is identical to other classes and can contain operations, attributes, as well as other associations. For example, a class called Student represents a student and has an association with a class called Course, which represents an educational course. The Student class can enroll in a course.

What is link and association in oops? ›

Association is a group of links having common structure and common behavior. Association depicts the relationship between objects of one or more classes. A link can be defined as an instance of an association.

What is association and its types in OOP? ›

Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.

What is the number 1 coding language? ›

JavaScript is the most common coding language in use today around the world. This is for a good reason: most web browsers utilize it and it's one of the easiest languages to learn. JavaScript requires almost no prior coding knowledge — once you start learning, you can practice and play with it immediately.

Is coding job stressful? ›

In general, coding is a fairly relaxing job. There is the flexibility of working remotely as a programmer, and in many cases there is the security of routine. However, as with any job, whether coding is stressful depends largely on the company you work with. Cultural pressures and tight deadlines can cause stress.

How much does a C++ programmer make a month? ›

As of Jan 17, 2023, the average annual pay for a C C++ Developer in the United States is $108,820 a year. Just in case you need a simple salary calculator, that works out to be approximately $52.32 an hour. This is the equivalent of $2,092/week or $9,068/month.

Why is C++ so hard to learn for beginners? ›

C++'s syntax itself isn't hard to learn, especially if you already know C. However, the versatility that makes C++ such a powerful and interesting language is itself the reason why many people find it hard.

How many days will it take to learn C++ after C? ›

If you already have a background in C programming, you can probably expect to spend about 3 or 4 months learning the additional features of C++. However, if you're starting from scratch with this language, you will probably spend over 6 months to learn it at the most basic level.

What pays more C++ or Python? ›

C++ vs Python Salaries: C++

According to Indeed, C++ developer salaries average $117,000 a year. Python developer salaries average $109,000 a year. These salaries do vary, but in general, the top-paid C++ developer is likely to make more than the top-paid Python developer.

Is C++ the hardest programming language? ›

The applications such as Google Chromium and a few Microsoft applications are developed using C++. It is one of the hardest programming languages because it has a complex syntax to support versatility. And it is best learned by those who have an understanding of C programming.

What type of coding is most in demand? ›

1. JavaScript. With increasing demand for dynamic, single page web applications, it's nearly impossible to become a professional software developer without learning JavaScript. According to Stack Overflow's 2022 Developer's Survey, JavaScript is the most popular language among developers for the tenth year in a row.

Does association help memory? ›

The reason that intentional associations work to improve memory is that memories are stored as a network of related items. These items are part of a shared whole. Any one item serves as a cue for retrieving other parts of the memory network.

What are the two types of association? ›

Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association.

Is it worth joining an association? ›

Opportunities to expand your professional reputation

A professional association allows you to meet likeminded professionals to ask for advice, share your ideas, become a member of a committee or volunteer to be a speaker. This might help you improve your reputation as an expert in your field.

How many associations are there? ›

There are 46,388trade / professional associations in the United States. Combined, these trade / professional associationsemploy 324,280 people, earn more than $53 billion in revenue each year, and have assets of $93 billion. Skip to: List of trade / professional associations.

What is association variables? ›

Association between two variables means the values of one variable relate in some way to the values of the other. It is usually measured by correlation for two continuous variables and by cross tabulation and a Chi-square test for two categorical variables.

What is association in learning? ›

Associative learning is defined as learning about the relationship between two separate stimuli, where the stimuli might range from concrete objects and events to abstract concepts, such as time, location, context, or categories. From: Handbook of Clinical Neurology, 2020.

Is it possible to learn C++ in one month? ›

It takes around 1 to 3 months to learn the basics and syntax of C++ programming. Gaining mastery in the C++ programming language can take around 2 years.

How much time does it take to learn C++ if I know C? ›

Case 1: If you have already learnt C language i mean if you have the knowledge of C programming then it will be easy for you to learn C++ as c++ is more easier than C language. Approximately you may need 25-30 days to learn C++ programming.

Can a average student learn C++? ›

Yes you can learn. Programming is not only for the brilliant people.

What is the hardest programming language? ›

Haskell. The language is named after a mathematician and is usually described to be one of the hardest programming languages to learn. It is a completely functional language built on lambda calculus.

Which is harder C or C++? ›

C++ was designed to be easier to use and to allow programmers to make efficient use of computer resources. C++ also has some similarities with C, but there are some important differences. C++ is a good choice for experienced programmers who want to learn a new programming language.

Is C++ hard if you know Python? ›

C++ has a lot of features and also has a comparatively difficult syntax. It is not that simple to write the C++ code. Python is easy to write and has a clear syntax. Hence writing Python programs is much easier when compared to C++.

Can I learn C++ without knowing C? ›

There is no need to learn C before learning C++. They are different languages. It is a common misconception that C++ is in some way dependent on C and not a fully specified language on its own. Just because C++ shares a lot of the same syntax and a lot of the same semantics, does not mean you need to learn C first.

Can I learn C++ in a week? ›

Can I learn C++ in a week? Sorry, but that's not going to happen. You can certainly learn a lot, and start writing and experimenting with some C++ code. But learning all of C++ in a week, not so much.

Is C++ easier than Python? ›

Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

Videos

1. Bjarne Stroustrup - The Essence of C++
(The University of Edinburgh)
2. C++ Review #1 for Beginners - Character ASCII Table, Size and Limits of Data Types - SavvyNik
(SavvyNik)
3. C++ Projects For Beginners 2022 | C++ Project Tutorial | Projects In C++ Language | Simplilearn
(Simplilearn)
4. CppCon 2017: Bjarne Stroustrup “Learning and Teaching Modern C++”
(CppCon)
5. 16.4 AutoRec - Rating Prediction with Autoencoders
(Sangram Kesari Ray)
6. Modern C++ Course: OpenCV 4 C++ in GNU/Linux (Tutorial 3, I. Vizzo, 2020)
(Cyrill Stachniss)
Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated: 03/22/2023

Views: 5654

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.