C + + Inheritance

Source: Internet
Author: User

C + + inheritance is almost the same as in Java, here's a simple example:

Main.cpp:

#include <iostream> #include "Box.h" #include "Carton.h" using std::cout;using std::endl;int Main () {Box Mybox ( 40.0,30.0,20.0); Carton Mycarton; Carton Candycarton ("Thin cardboard") cout << endl<< "Mybox occupies" << sizeof mybox << "bytes" &L T;<endl;cout << "Mycarton occupies" << sizeof Mycarton << "bytes" <<endl;cout << "Candyc Arton occupies "<<sizeof candycarton <<" bytes "<<endl;return 0;}


Box.h:

#ifndef box_h#define box_hclass box{public:box (double lv=1.0,double wv=1.0,double hv=1.0);p rivate:double length; Double width;double height;}; #endif


Carton.h:

#ifndef carton_h#define carton_h#include "Box.h" Class Carton:public Box{public:carton (const char* pstr= "Cardboard"); ~ Carton ();p rivate:char* pmaterial;}; #endif


Box.cpp:

#include "Box.h" Box::box (double lv,double wv,double HV): Length (LV), Width (WV), height (HV) {}


Carton.cpp:

#include "Carton.h" #include <cstring> #include <iostream>carton::carton (const char* pStr) {pmaterial=new Char[strlen (PSTR) +1]; strcpy (PMATERIAL,PSTR);} Carton::~carton () {delete[] pmaterial;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.